Skip to content

Commit

Permalink
Implement q_merge function
Browse files Browse the repository at this point in the history
Implement q_merge() to merge all queues into one sorted queue, which can
be sorted in ascending or descending order.
  • Loading branch information
aftuta85 committed Mar 20, 2024
1 parent 0f6c922 commit d749d0b
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions queue.c
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,18 @@ int q_descend(struct list_head *head)
* order */
int q_merge(struct list_head *head, bool descend)
{
// https://leetcode.com/problems/merge-k-sorted-lists/
return 0;
if (!head || list_empty(head))
return 0;

queue_contex_t *qc_first = list_first_entry(head, queue_contex_t, chain);
queue_contex_t *curr = NULL;
list_for_each_entry (curr, head, chain) {
if (qc_first == curr)
continue;
list_splice_init(curr->q, qc_first->q);
qc_first->size += curr->size;
curr->size = 0;
}
q_sort(qc_first->q, descend);
return qc_first->size;
}

0 comments on commit d749d0b

Please sign in to comment.