Skip to content

Commit 97d2cb0

Browse files
committed
Update reverse and reverseK functions:
Fix q_reverse to correctly swap prev and next pointers while traversing the queue. The previous implementation did not properly update the head node's next and prev pointers, leading to potential list corruption. Key fixes: Ensure that head->next and head->prev are correctly updated. Traverse the list safely without modifying pointers before they are used. Maintain circular doubly linked list structure. Change-Id: I31bdc6ec4d67287c16852fefbdad13f389ef97fb
1 parent 5567955 commit 97d2cb0

File tree

1 file changed

+21
-9
lines changed

1 file changed

+21
-9
lines changed

queue.c

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ element_t *q_remove_head(struct list_head *head, char *sp, size_t bufsize)
9595
strncpy(sp, node->value, bufsize - 1);
9696
sp[bufsize - 1] = '\0';
9797
}
98+
9899
return node;
99100
}
100101

@@ -114,6 +115,7 @@ element_t *q_remove_tail(struct list_head *head, char *sp, size_t bufsize)
114115
strncpy(sp, node->value, bufsize - 1);
115116
sp[bufsize - 1] = '\0';
116117
}
118+
117119
return node;
118120
}
119121

@@ -220,29 +222,34 @@ void q_reverse(struct list_head *head)
220222
return;
221223
}
222224

223-
struct list_head *cur = head->prev;
225+
struct list_head *cur = head, *tmp;
224226

225-
while (cur != head) {
226-
struct list_head *prev = cur->prev;
227-
list_move(cur, head);
228-
cur = prev;
229-
}
227+
do {
228+
tmp = cur->next;
229+
cur->next = cur->prev;
230+
cur->prev = tmp;
231+
cur = tmp;
232+
} while (cur != head);
233+
return;
230234
}
231235

232236
/* Reverse the nodes of the list k at a time */
233237
void q_reverseK(struct list_head *head, int k)
234238
{
235-
if (!head || list_empty(head) || k <= 1)
239+
if (!head || list_empty(head) || k <= 1) {
236240
return;
241+
}
237242

238243
struct list_head *cur, *next;
239244
int count = 0;
240245

241-
list_for_each (cur, head)
246+
list_for_each (cur, head) {
242247
count++;
248+
}
243249

244-
if (count < k)
250+
if (count < k) {
245251
return;
252+
}
246253

247254
cur = head->next;
248255

@@ -255,9 +262,14 @@ void q_reverseK(struct list_head *head, int k)
255262
break;
256263
list_move_tail(next, head);
257264
}
265+
266+
group_tail->prev = cur->prev;
267+
cur->prev->next = group_tail;
268+
258269
cur = group_tail->next;
259270
count -= k;
260271
}
272+
return;
261273
}
262274

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

0 commit comments

Comments
 (0)