Skip to content

Commit 6c2c172

Browse files
committed
Implement q_ascend
Previously, q_ascend was a placeholder and did nothing. Now it correctly removes nodes that violate ascending order, ensuring the remaining elements form a non-decreasing sequence. Change-Id: Id51a9e7348010523d6fc041e851376762bb06ab9
1 parent a56881b commit 6c2c172

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

queue.c

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,28 @@ void q_sort(struct list_head *head, bool descend) {}
190190
int q_ascend(struct list_head *head)
191191
{
192192
// https://leetcode.com/problems/remove-nodes-from-linked-list/
193-
return 0;
193+
if (!head || list_empty(head))
194+
return false;
195+
struct list_head *cur = head->next, *next, *node;
196+
while (cur != head) {
197+
int remove = 0;
198+
next = node = cur->next;
199+
while (node != head) {
200+
struct list_head *temp = node->next;
201+
if (strcmp(list_entry(cur, element_t, list)->value,
202+
list_entry(node, element_t, list)->value) > 0) {
203+
remove = 1;
204+
}
205+
node = temp;
206+
}
207+
if (remove) {
208+
next = cur->next;
209+
list_del(cur);
210+
q_release_element(list_entry(cur, element_t, list));
211+
}
212+
cur = next;
213+
}
214+
return q_size(head);
194215
}
195216

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

0 commit comments

Comments
 (0)