From aff642ca1ed360b27d009cdf89966cbe8d59c65a Mon Sep 17 00:00:00 2001 From: Aaron Liao Date: Thu, 21 Mar 2024 17:04:41 +0800 Subject: [PATCH] Implement q_reverseK function: Implement q_reverseK() to reverse the nodes of the list k at a time. --- queue.c | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/queue.c b/queue.c index e0bb9a494..825671fe4 100644 --- a/queue.c +++ b/queue.c @@ -217,7 +217,23 @@ void q_reverse(struct list_head *head) /* Reverse the nodes of the list k at a time */ void q_reverseK(struct list_head *head, int k) { - // https://leetcode.com/problems/reverse-nodes-in-k-group/ + if (!head || list_empty(head)) + return; + + int count = 1; + struct list_head *curr = head->next, *prev = head, *nxt = curr->next; + LIST_HEAD(tmp_list); + while (curr != head) { + if (count % k == 0) { + list_cut_position(&tmp_list, prev, curr); + q_reverse(&tmp_list); + list_splice_init(&tmp_list, prev); + prev = nxt->prev; + } + count++; + curr = nxt; + nxt = nxt->next; + } } static void merge(struct list_head *head,