Skip to content

Commit 11bbebe

Browse files
committed
Implemented merge function
Implemented q_merge to merge multiple queues into wa single sorted queue. Ensured correct queue merging by moving elements while maintaining list integrity. Properly updated queue size after merging. Used INIT_LIST_HEAD() to reset sub-queues after merging, preventing redundant merges. Change-Id: I52c8e70d3f75055156758421f6c4d07213b8a708
1 parent 5cebf2f commit 11bbebe

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

queue.c

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -420,5 +420,38 @@ int q_descend(struct list_head *head)
420420
* order */
421421
int q_merge(struct list_head *head, bool descend)
422422
{
423-
return 0;
423+
if (!head || list_empty(head) || list_is_singular(head))
424+
return 0;
425+
426+
struct list_head *cur, *next;
427+
queue_contex_t *main_ctx = list_entry(head->next, queue_contex_t, chain);
428+
if (!main_ctx->q)
429+
return 0;
430+
431+
int total_size = main_ctx->size;
432+
433+
list_for_each_safe (cur, next, head) {
434+
queue_contex_t *ctx = list_entry(cur, queue_contex_t, chain);
435+
if (ctx == main_ctx || !ctx->q || list_empty(ctx->q))
436+
continue;
437+
438+
struct list_head *sub_queue = ctx->q;
439+
while (!list_empty(sub_queue)) {
440+
struct list_head *node = sub_queue->next;
441+
list_del(node);
442+
list_add_tail(node, main_ctx->q);
443+
}
444+
445+
INIT_LIST_HEAD(ctx->q);
446+
total_size += ctx->size;
447+
ctx->size = 0;
448+
}
449+
450+
main_ctx->q->prev->next = main_ctx->q;
451+
main_ctx->q->next->prev = main_ctx->q;
452+
453+
q_sort(main_ctx->q, descend);
454+
455+
main_ctx->size = total_size;
456+
return main_ctx->size;
424457
}

0 commit comments

Comments
 (0)