Skip to content

Commit 5567955

Browse files
committed
Implement reverse and reverseK functions
Add q_reverse to reverse the entire queue by swapping next and prev pointers in a single pass, ensuring O(n) time complexity. This function properly updates the head node to maintain a circular doubly linked list. Add q_reverseK to reverse every k nodes in the queue while keeping the last group unchanged if its size is smaller than k.The implementation uses list_move_tail() for efficient node reordering, following the Linux Kernel linked list style. Change-Id: I02a0975f23dadaabfc1cf1c2f830e7ce958325e1
1 parent 3f716d0 commit 5567955

File tree

1 file changed

+54
-2
lines changed

1 file changed

+54
-2
lines changed

queue.c

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,16 +196,68 @@ bool q_delete_dup(struct list_head *head)
196196
/* Swap every two adjacent nodes */
197197
void q_swap(struct list_head *head)
198198
{
199+
if (!head || list_empty(head) || head->next == head->prev) {
200+
return;
201+
}
202+
203+
struct list_head *cur = head->next;
204+
205+
while (cur != head && cur->next != head) {
206+
struct list_head *first = cur;
207+
struct list_head *second = cur->next;
208+
209+
list_move(first, second);
210+
211+
cur = first->next;
212+
}
199213
// https://leetcode.com/problems/swap-nodes-in-pairs/
200214
}
201215

202216
/* Reverse elements in queue */
203-
void q_reverse(struct list_head *head) {}
217+
void q_reverse(struct list_head *head)
218+
{
219+
if (!head || list_empty(head) || head->next == head->prev) {
220+
return;
221+
}
222+
223+
struct list_head *cur = head->prev;
224+
225+
while (cur != head) {
226+
struct list_head *prev = cur->prev;
227+
list_move(cur, head);
228+
cur = prev;
229+
}
230+
}
204231

205232
/* Reverse the nodes of the list k at a time */
206233
void q_reverseK(struct list_head *head, int k)
207234
{
208-
// https://leetcode.com/problems/reverse-nodes-in-k-group/
235+
if (!head || list_empty(head) || k <= 1)
236+
return;
237+
238+
struct list_head *cur, *next;
239+
int count = 0;
240+
241+
list_for_each (cur, head)
242+
count++;
243+
244+
if (count < k)
245+
return;
246+
247+
cur = head->next;
248+
249+
while (count >= k) {
250+
struct list_head *group_tail = cur;
251+
int i = 0;
252+
253+
list_for_each_safe (cur, next, head) {
254+
if (++i == k)
255+
break;
256+
list_move_tail(next, head);
257+
}
258+
cur = group_tail->next;
259+
count -= k;
260+
}
209261
}
210262

211263
/* Sort elements of queue in ascending/descending order */

0 commit comments

Comments
 (0)