Skip to content

Commit

Permalink
Implement q_swap function
Browse files Browse the repository at this point in the history
Perform the operation of swapping pairs of entries in the queue, without swapping if there is only one entry left at the end.
  • Loading branch information
aa860630 committed Mar 1, 2024
1 parent f85be9d commit a371b33
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion queue.c
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,37 @@ bool q_delete_dup(struct list_head *head)
/* Swap every two adjacent nodes */
void q_swap(struct list_head *head)
{
// https://leetcode.com/problems/swap-nodes-in-pairs/
// https://leetcode.com/problems/swap-nodes-in-pairs//
struct list_head *cur = head;
struct list_head *first = head->next;
struct list_head *second = first->next;

while (first != head) {
if (second == head) {
cur->next = first;
first->prev = cur;

first->next = head;
head->prev = first;

break;
} else {
first->next = second->next;
second->next->prev = first;

second->next = first;
first->prev = second;

cur->next = second;
second->prev = cur;

cur = first;
first = first->next;
second = first->next;
}
cur->next = head;
head->prev = cur;
}
}

/* Reverse elements in queue */
Expand Down

0 comments on commit a371b33

Please sign in to comment.