/* * description: 链表归并排序示例 * writeby: nick * date: 2012-10-23 16:35 * */ #include <iostream> #define maxN 10 using namespace std; struct node { int item; node *next; node(int n){item=n; next=0;} }; typedef node *link; link merge(link a, link b) //合并a b 链表 { node dummy(0); link head=&dummy, c=head; while((a!=0) && (b!=0)) { 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==0)? b : a; return head -> next; } link mergesort(link c) { if(c==0 || c->next==0) return c; link a=c, b=c->next; while(b!=0 && b->next!=0) { a=a->next; b=b->next->next; } b=a->next; a->next=0; //把c分成两部分 return merge(mergesort(c), mergesort(b)); } int main() { link head1 = new node(2); head1->next = new node(4); head1->next->next = new node(6); head1->next->next->next = new node(3); head1->next->next->next->next = new node(5); link head = mergesort(head1); while(head != 0) { cout << head->item; head = head->next; } return 0; }