您的位置:首页 > 其它

采用队列实现自底向上链表归并排序

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);}
程序运行结果:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: