Skip to content

Commit a71f613

Browse files
committed
Implement q_ascend and q_descend function
Add q_ascend and q_descend function that remove every node which has a node with a strictly greater/less value anywhere to the right side of it.The function check from backward if current value is greater/less than maximum/minimum, if so, change the maximum/minimum. If not delete current node and move to the next node. Change-Id: I62a17aced94af458beb72ec26cf16c63d18fb43f
1 parent 1e442f2 commit a71f613

File tree

1 file changed

+42
-4
lines changed

1 file changed

+42
-4
lines changed

queue.c

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -364,15 +364,53 @@ void q_sort(struct list_head *head, bool descend)
364364
int q_ascend(struct list_head *head)
365365
{
366366
// https://leetcode.com/problems/remove-nodes-from-linked-list/
367-
return 0;
367+
if (!head || list_empty(head)) {
368+
return 0;
369+
}
370+
371+
const char *min = list_entry(head->prev, element_t, list)->value;
372+
373+
struct list_head *current, *safe;
374+
for (current = (head)->prev, safe = current->prev; current != head;
375+
current = safe, safe = current->prev) {
376+
element_t *current_entry = list_entry(current, element_t, list);
377+
if (strcmp(current_entry->value, min) > 0) {
378+
list_del(current);
379+
free(current_entry->value);
380+
free(current_entry);
381+
} else if (strcmp(current_entry->value, min) < 0) {
382+
min = current_entry->value;
383+
}
384+
}
385+
386+
return q_size(head);
368387
}
369388

370-
/* Remove every node which has a node with a strictly greater value anywhere to
371-
* the right side of it */
389+
/* Remove every node which has a node with a strictly greater value anywhere
390+
* to the right side of it */
372391
int q_descend(struct list_head *head)
373392
{
374393
// https://leetcode.com/problems/remove-nodes-from-linked-list/
375-
return 0;
394+
if (!head || list_empty(head)) {
395+
return 0;
396+
}
397+
398+
const char *max = list_entry(head->prev, element_t, list)->value;
399+
400+
struct list_head *current, *safe;
401+
for (current = (head)->prev, safe = current->prev; current != head;
402+
current = safe, safe = current->prev) {
403+
element_t *current_entry = list_entry(current, element_t, list);
404+
if (strcmp(current_entry->value, max) < 0) {
405+
list_del(current);
406+
free(current_entry->value);
407+
free(current_entry);
408+
} else if (strcmp(current_entry->value, max) > 0) {
409+
max = current_entry->value;
410+
}
411+
}
412+
413+
return q_size(head);
376414
}
377415

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

0 commit comments

Comments
 (0)