采用队列实现自底向上链表归并排序
2015-08-16 22:06
246 查看
源代码如下:
#include <stdio.h>#include <stdlib.h>typedef struct node *link;struct node{int item ;link next;};typedef struct QUEUEnode* queue;struct QUEUEnode{link item ;queue next;};static queue head , tail;queue NEW(link item, queue next){queue x = (queue) malloc(sizeof *x);x->item = item;x->next = next;return x;}void QUEUEinit(int maxN){head = NULL;}int QUEUEempty(){return head == NULL;}void QUEUEput(link item){if(head == NULL){head =(tail = NEW(item,head)) ;return;}tail->next = NEW(item,tail->next);tail = tail->next;}link QUEUEget(){link item = head->item;queue t = head->next;free(head);head = t;return item;}void printLink(link l){while(l!=NULL){printf("%d-->",l->item);l = l->next;}printf("\n");}link create(int n){int i ;link head = (link) malloc(sizeof *head ), p, q;head -> item = 1;q = head;for(i = 2 ; i <= 20; i+=n){p = (link)malloc(sizeof(*p));p->item = i;q->next = p;q = p;}q->next = NULL ;return head;}link createRand(int n){int i ;link head = (link) malloc(sizeof *head ), p, q;head -> item = 1;q = head;for(i = 2 ; i <= 20; i+=n){p = (link)malloc(sizeof(*p));p->item = rand()%100;q->next = p;q = p;}q->next = NULL ;return head;}//归并两个有序的链表成一个有序的链表link mergeLink(link a , link b){struct node head ;link c = &head;while(a!=NULL && b!=NULL)if(a->item<b->item){c->next=a ; c = a; a = a->next;}else{c->next=b ; c = b; b= b->next;}c->next=a==NULL?b:a ;return head.next;}//采用自底向上归并排序link mergeSort(link t){link u;for(QUEUEinit(40);t!=NULL;t=u){u=t->next; t->next= NULL;QUEUEput(t);}t = QUEUEget();while(!QUEUEempty()){QUEUEput(t);t = mergeLink(QUEUEget(),QUEUEget());}return t;}main(){link a = create(2);link b = create(3);printLink(a);printLink(b);link c = mergeLink(a,b);printLink(c);link d = createRand(2);printLink(d);link e = mergeSort(d);printLink(e);}程序运行结果:
相关文章推荐
- JavaScript--点击颜色,为主题更换背景颜色
- NSMakeRange,substringWithRange,substringToIndex,substringFromIndex区别和联系
- scala学习之:List的foldLeft、foldRight操作实战
- Microsoft Dynamics CRM server 2013升级 2015(一)提前准备及补丁
- C++命名空间
- 亿唐
- c# 自定义控件
- 九度oj-1158-买房子
- 欢迎使用CSDN-markdown编辑器
- POJ-2195
- bzoj 2595 斯坦纳树
- 数据结构和算法系列15 线索二叉树
- c++primer之try语句块和异常处理
- 连接器 ELF格式 装载可执行文件与虚拟进程空间
- python修饰器
- Codeforces554C:Kyoya and Colored Balls(组合数学计算+费马小定理)
- Opencv 三次样条曲线(Cubic Spline)插值
- 数据结构:二叉树(前,中,后,层次)非递归遍历。
- 进程间通信概述
- Opencv 三次样条曲线(Cubic Spline)插值