单链表的归并排序
#include<iostream> #include<time.h> using namespace std; //链表的归并排序 struct listnode{ int value; listnode* next; listnode(int value):value(value),next(NULL){} }; listnode* find_mid(listnode* head){ if(head==NULL)return NULL; listnode* fast=head; listnode* slow = head; while(fast->next!=NULL){ if(fast->next->next!=NULL){ fast = fast->next->next; slow = slow->next; }else break; } return slow; } listnode* merge_list(listnode* list1,listnode* list2){ if(list1==NULL)return list2; if(list2==NULL)return list1; listnode* cur = NULL; listnode* head=NULL; if(list1->value<=list2->value){ head = list1; list1 = list1->next; }else{ head = list2; list2 = list2->next; } listnode* pnode = head; while(list1&&list2){ if(list1->value<=list2->value){ cur = list1; list1 = list1->next; }else{ cur = list2; list2 = list2->next; } pnode->next = cur; pnode = pnode->next; } if(list1 == NULL)pnode->next = list2; if(list2 == NULL)pnode->next = list1; return head; } listnode* merge_sort(listnode* head){ if(head==NULL||head->next==NULL)return head; listnode* mid = find_mid(head); listnode* m = mid->next; mid->next = NULL; listnode* list1 = merge_sort(head); listnode* list2 = merge_sort(m); head = merge_list(list1,list2); return head; } int main(){ int length = 10; listnode* r = new listnode(0); listnode* head = r; for(int i=0;i<length;i++){ r->next = new listnode(rand()%30); r = r->next; } listnode* p = merge_sort(head->next); delete head; head= p; while(head){ listnode* temp = head; head = head->next; cout<<temp->value<<endl; delete temp; } system("pause"); }