Skip to content

Commit fcf15dc

Browse files
committed
Implement q_descend and q_ascend
Find the max or min node from the tail of the list and delete the node which smaller or bigger than it. Change-Id: I48d97e1b31d16679a4c14d6bd5228683296fffa9
1 parent 73d4cd8 commit fcf15dc

1 file changed

Lines changed: 38 additions & 2 deletions

File tree

queue.c

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -220,15 +220,51 @@ void q_sort(struct list_head *head, bool descend) {}
220220
int q_ascend(struct list_head *head)
221221
{
222222
// https://leetcode.com/problems/remove-nodes-from-linked-list/
223-
return 0;
223+
if (!head || list_empty(head))
224+
return 0;
225+
226+
struct list_head *min = head->prev, *curr = min->prev;
227+
const element_t *min_ele = list_entry(min, element_t, list);
228+
229+
while (curr != head) {
230+
element_t *curr_ele = list_entry(curr, element_t, list);
231+
struct list_head *prev = curr->prev;
232+
if (strcmp(curr_ele->value, min_ele->value) < 0) {
233+
min_ele = curr_ele;
234+
} else {
235+
list_del(curr);
236+
q_release_element(curr_ele);
237+
}
238+
239+
curr = prev;
240+
}
241+
return q_size(head);
224242
}
225243

226244
/* Remove every node which has a node with a strictly greater value anywhere to
227245
* the right side of it */
228246
int q_descend(struct list_head *head)
229247
{
230248
// https://leetcode.com/problems/remove-nodes-from-linked-list/
231-
return 0;
249+
if (!head || list_empty(head))
250+
return 0;
251+
252+
struct list_head *max = head->prev, *curr = max->prev;
253+
const element_t *max_ele = list_entry(max, element_t, list);
254+
255+
while (curr != head) {
256+
element_t *curr_ele = list_entry(curr, element_t, list);
257+
struct list_head *prev = curr->prev;
258+
if (strcmp(curr_ele->value, max_ele->value) < 0) {
259+
max_ele = curr_ele;
260+
} else {
261+
list_del(curr);
262+
q_release_element(curr_ele);
263+
}
264+
265+
curr = prev;
266+
}
267+
return q_size(head);
232268
}
233269

234270
/* Merge two sorted list into list l */

0 commit comments

Comments
 (0)