Skip to content

Commit 3d4c601

Browse files
committed
Implement q_ascend and q_descend
Add q_monotonic as a helper function to remove nodes from a linked list if a node with a strictly greater or lesser value exists to its right, depending on the descend parameter. The q_monotonic function iterates from the end (descend=true) or start (descend=false), tracking the maximum value seen so far with strcmp, and deletes nodes violating the monotonic condition. The q_ascend and q_descend functions call q_monotonic with descend set to false and true, respectively. Change-Id: Ia3ce39acbf5578a6e4109e58257dbd18a6eebd74
1 parent 311940e commit 3d4c601

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

queue.c

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,20 +226,49 @@ void q_reverseK(struct list_head *head, int k)
226226
/* Sort elements of queue in ascending/descending order */
227227
void q_sort(struct list_head *head, bool descend) {}
228228

229+
/* Remove every node which has a node with a strictly less/greater value
230+
* anywhere to the right side of it according to descend flag */
231+
int q_monotonic(struct list_head *head, bool descend)
232+
{
233+
if (!head || list_empty(head))
234+
return 0;
235+
236+
element_t *node, *safe;
237+
node = descend ? list_last_entry(head, element_t, list)
238+
: list_first_entry(head, element_t, list);
239+
safe = list_entry(descend ? node->list.prev : node->list.next, element_t,
240+
list);
241+
/* cppcheck-suppress constVariablePointer */
242+
char *max = node->value;
243+
244+
while (&node->list != head) {
245+
if (strcmp(max, node->value) > 0) {
246+
list_del_init(&node->list);
247+
q_release_element(node);
248+
} else
249+
max = node->value;
250+
251+
node = safe;
252+
safe = list_entry(descend ? node->list.prev : node->list.next,
253+
element_t, list);
254+
}
255+
return q_size(head);
256+
}
257+
229258
/* Remove every node which has a node with a strictly less value anywhere to
230259
* the right side of it */
231260
int q_ascend(struct list_head *head)
232261
{
233262
// https://leetcode.com/problems/remove-nodes-from-linked-list/
234-
return 0;
263+
return q_monotonic(head, false);
235264
}
236265

237266
/* Remove every node which has a node with a strictly greater value anywhere to
238267
* the right side of it */
239268
int q_descend(struct list_head *head)
240269
{
241270
// https://leetcode.com/problems/remove-nodes-from-linked-list/
242-
return 0;
271+
return q_monotonic(head, true);
243272
}
244273

245274
/* Merge all the queues into one sorted queue, which is in ascending/descending

0 commit comments

Comments
 (0)