Skip to content

Commit fd64306

Browse files
committed
Implement q_merge function
Add q_merge function that merge all the queues into one sorted queue.The function count the needed merge times,then iterate through every queue. For every iteration, input the first and second entry of the queue into merge_queue function.The auxiliary function take the node of two entry and compare it for every loop.Put the smaller one into the temp queue. Finally, spice the rest of the remain queue to the tail of the new queue. Change-Id: Ibec82e4ddd550fb74a94f1b99e3c3fe1c79b140a
1 parent a71f613 commit fd64306

File tree

1 file changed

+50
-3
lines changed

1 file changed

+50
-3
lines changed

queue.c

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -413,10 +413,57 @@ int q_descend(struct list_head *head)
413413
return q_size(head);
414414
}
415415

416-
/* Merge all the queues into one sorted queue, which is in ascending/descending
417-
* order */
416+
/* Merge all the queues into one sorted queue, which is in
417+
* ascending/descending order */
418+
419+
int merge_queue(struct list_head *first, struct list_head *second)
420+
{
421+
if (!first || !second) {
422+
return 0;
423+
}
424+
425+
LIST_HEAD(tmp);
426+
while (!list_empty(first) && !list_empty(second)) {
427+
element_t *element_1 = list_first_entry(first, element_t, list);
428+
element_t *element_2 = list_first_entry(second, element_t, list);
429+
element_t *element_min = strcmp(element_1->value, element_2->value) < 0
430+
? element_1
431+
: element_2;
432+
list_move_tail(&element_min->list, &tmp);
433+
}
434+
list_splice_tail_init(first, &tmp);
435+
list_splice_tail_init(second, &tmp);
436+
list_splice(&tmp, first);
437+
return q_size(first);
438+
}
439+
418440
int q_merge(struct list_head *head, bool descend)
419441
{
420442
// https://leetcode.com/problems/merge-k-sorted-lists/
421-
return 0;
443+
if (!head || list_empty(head)) {
444+
return 0;
445+
} else if (list_is_singular(head)) {
446+
return q_size(list_first_entry(head, queue_contex_t, chain)->q);
447+
}
448+
449+
int size = q_size(head);
450+
int count = (size % 2) ? size / 2 + 1 : size / 2;
451+
int queue_size = 0;
452+
453+
for (int i = 0; i < count; i++) {
454+
queue_contex_t *first = list_first_entry(head, queue_contex_t, chain);
455+
queue_contex_t *second =
456+
list_entry(first->chain.next, queue_contex_t, chain);
457+
458+
while (!list_empty(first->q) && !list_empty(second->q)) {
459+
queue_size = merge_queue(first->q, second->q);
460+
list_move_tail(&second->chain, head);
461+
first = list_entry(first->chain.next, queue_contex_t, chain);
462+
second = list_entry(first->chain.next, queue_contex_t, chain);
463+
}
464+
}
465+
if (descend) {
466+
q_reverse(head);
467+
}
468+
return queue_size;
422469
}

0 commit comments

Comments
 (0)