链表的归并排序
特别注意取中值函数的书写
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *sortList(ListNode *head) { if(!head||!head->next) return head; ListNode *mid=GetMid(head); ListNode *midnext=mid->next; mid->next=NULL; ListNode *lefthead=sortList(head); ListNode *righthead=sortList(midnext); return Merge(lefthead,righthead); } ListNode *GetMid(ListNode *head){ if(!head||!head->next) return head; ListNode *pNode1=head->next;//0,1,2,3 middle 1 ListNode *pNode2=head; while(pNode1&&pNode1->next){// if pNode1==NULL pNode1=pNode1->next->next; pNode2=pNode2->next; } return pNode2; } ListNode *Merge(ListNode *lefthead,ListNode*righthead){ ListNode *runner= new ListNode(10000); ListNode *head=lefthead->val<righthead->val?lefthead:righthead; while(lefthead&&righthead){ if(lefthead->val<righthead->val){ runner->next=lefthead; lefthead=lefthead->next; runner=runner->next; } else{ runner->next=righthead; righthead=righthead->next; runner=runner->next; } } if(lefthead) runner->next=lefthead; else if(righthead) runner->next=righthead; return head; } };
原文地址:http://blog.csdn.net/eliza1130/article/details/44756069