c语言实现k个有序链表合并,K个有序链表共N个结点在O(NlgK)时间合并为一个新的有序链表实现文件C语言...

先是在 main () 函数中构造输入.之后调用主例程解决问题.可以看到,主例程是相当精妙的.这当然是需要前面数据结构的正确.

/*MergeQueue.c -- O (NlogK) 时间将K个有序队列合并为一个新有序队列*/

#include "Queue.h"

#include "PriorityQueue.h"

#define SIZE (5)

int main (void) ;

BOOL merge (const Queue * const array, const int number, Queue * const pNewQueue) ;

int main (void)

{

Queue array[SIZE] ;

Queue q1, q2, q3, q4, q5, newQueue ;

Item item ;

/*Artificial element.*/

Initialize_Q (&q1) ;

Initialize_Q (&q2) ;

Initialize_Q (&q3) ;

Initialize_Q (&q4) ;

Initialize_Q (&q5) ;

item = 1 ;

EnQueue_Q (&q1, item) ;

item = 2 ;

EnQueue_Q (&q1, item) ;

item = 2 ;

EnQueue_Q (&q1, item) ;

item = 4 ;

EnQueue_Q (&q1, item) ;

item = 20 ;

EnQueue_Q (&q1, item) ;

item = 3 ;

EnQueue_Q (&q2, item) ;

item = 7 ;

EnQueue_Q (&q2, item) ;

item = 8 ;

EnQueue_Q (&q2, item) ;

item = 8 ;

EnQueue_Q (&q2, item) ;

item = 9 ;

EnQueue_Q (&q2, item) ;

item = 16 ;

EnQueue_Q (&q2, item) ;

item = 45 ;

EnQueue_Q (&q3, item) ;

item = 56 ;

EnQueue_Q (&q3, item) ;

item = 77 ;

EnQueue_Q (&q3, item) ;

item = 14 ;

EnQueue_Q (&q4, item) ;

item = 67 ;

EnQueue_Q (&q4, item) ;

item = 78 ;

EnQueue_Q (&q4, item) ;

item = 89 ;

EnQueue_Q (&q4, item) ;

item = 90 ;

EnQueue_Q (&q4, item) ;

item = 92 ;

EnQueue_Q (&q4, item) ;

item = 11 ;

EnQueue_Q (&q5, item) ;

item = 22 ;

EnQueue_Q (&q5, item) ;

item = 33 ;

EnQueue_Q (&q5, item) ;

item = 34 ;

EnQueue_Q (&q5, item) ;

item = 35 ;

EnQueue_Q (&q5, item) ;

item = 37 ;

EnQueue_Q (&q5, item) ;

item = 45 ;

EnQueue_Q (&q5, item) ;

item = 56 ;

EnQueue_Q (&q5, item) ;

item = 67 ;

EnQueue_Q (&q5, item) ;

array[0] = q1 ;

array[1] = q2 ;

array[2] = q3 ;

array[3] = q4 ;

array[4] = q5 ;

/*Initialize new queue.*/

Initialize_Q (&newQueue) ;

/*It's so attractive!*/

merge (array, SIZE, &newQueue) ;

Release_Q (&q1) ;

Release_Q (&q2) ;

Release_Q (&q3) ;

Release_Q (&q4) ;

Release_Q (&q5) ;

Release_Q (&newQueue) ;

return 0 ;

}

/*O (NlogK)*/

BOOL merge (const Queue * const array, const int number, Queue * const pNewQueue)

{

PriorityQueue pq ;

PriorityNode temp ;

int i ;

if (number <= 0 || FALSE == Initialize_P (&pq, number))

return FALSE ;

/*Bulid heap.*/

for (i = 0; i < number; i++)

Insert_P (&pq, array[i] -> front) ;

/*Core loop.*/

while (FALSE == IsEmpty_P (&pq))

{

temp = DeleteMin_P (&pq) ;

EnQueue_Q (pNewQueue, temp -> item) ;

if (temp -> next != NULL)

Insert_P (&pq, temp -> next) ;

}

Release_P (&pq) ;

return TRUE ;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值