Skip to content

Commit b6e2fb4

Browse files
committed
Implement q_reverse
Previously, q_reverse was an empty placeholder. This commit implements the function to properly reverse the elements of a queue using a safe traversal approach. Change-Id: I7fd9c076d1b690134a553ac18238fe7bbdc3a3ba
1 parent 0f5cb67 commit b6e2fb4

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

queue.c

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,20 @@ void q_swap(struct list_head *head)
138138
}
139139

140140
/* Reverse elements in queue */
141-
void q_reverse(struct list_head *head) {}
141+
void q_reverse(struct list_head *head)
142+
{
143+
if (!head || list_empty(head))
144+
return;
145+
struct list_head *curr, *safe, *temp;
146+
list_for_each_safe (curr, safe, head) {
147+
temp = curr->next;
148+
curr->next = curr->prev;
149+
curr->prev = temp;
150+
}
151+
temp = head->next;
152+
head->next = head->prev;
153+
head->prev = temp;
154+
}
142155

143156
/* Reverse the nodes of the list k at a time */
144157
void q_reverseK(struct list_head *head, int k)

0 commit comments

Comments
 (0)