Skip to content

Commit 5cebf2f

Browse files
committed
Implemented q_ascend() to remove nodes that have
a strictly smaller value anywhere to the right. Ensured the function runs in O(n) time by iterating from the tail and keeping track of the minimum value. Fixed head->prev updates to maintain the doubly linked list structure. Prevented segmentation faults by correctly handling memory deallocation. Change-Id: I76c010c1bea1ef643562bb31242cf459ca82c812
1 parent 3d95a49 commit 5cebf2f

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

queue.c

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -356,29 +356,33 @@ void q_sort(struct list_head *head, bool descend)
356356
* the right side of it */
357357
int q_ascend(struct list_head *head)
358358
{
359-
if (!head || list_empty(head) || head->next == head->prev) {
359+
if (!head || list_empty(head))
360360
return 0;
361-
}
362361

363-
struct list_head *cur = head->prev, *prev_max = cur, *tmp;
362+
struct list_head *cur = head->prev, *prev;
363+
const element_t *min_elem = list_entry(cur, element_t, list);
364364
int count = 1;
365365

366-
list_for_each_safe (cur, tmp, head) {
367-
element_t *e_cur = list_entry(cur, element_t, list);
368-
const element_t *e_max = list_entry(prev_max, element_t, list);
366+
while (cur != head) {
367+
prev = cur->prev;
368+
element_t *e = list_entry(cur, element_t, list);
369369

370-
if (strcmp(e_cur->value, e_max->value) >= 0) {
371-
prev_max = cur;
372-
count++;
373-
} else {
370+
if (strcmp(e->value, min_elem->value) > 0) {
374371
list_del(cur);
375-
free(e_cur->value);
376-
free(e_cur);
372+
free(e->value);
373+
free(e);
374+
} else {
375+
min_elem = e;
376+
count++;
377377
}
378+
379+
cur = prev;
378380
}
379381

382+
head->prev = min_elem->list.prev;
383+
head->prev->next = head;
384+
380385
return count;
381-
// https://leetcode.com/problems/remove-nodes-from-linked-list/
382386
}
383387

384388
/* Remove every node which has a node with a strictly greater value anywhere to

0 commit comments

Comments
 (0)