标签:
#include <iostream> using namespace std; /** * 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==NULL) return NULL; if(head->next==NULL) return head; ListNode *plft=head,*prgt=head; while(prgt->next!=NULL){ if(prgt->next!=NULL) prgt=prgt->next; if(prgt->next!=NULL) prgt=prgt->next; plft = plft->next; } if(prgt==head->next){ if(head->val>prgt->val){ prgt->next = head; head->next = NULL; head = prgt; } return head; } prgt = plft->next; plft->next = NULL; plft = sortList(head); prgt = sortList(prgt); ListNode * ret,*leave,*tmp,*tmp2; ret = plft->val<=prgt->val?plft:prgt; tmp = ret; leave = plft->val<=prgt->val?prgt:plft; while(leave!=NULL){ while(tmp->next!=NULL&&tmp->next->val<=leave->val) tmp= tmp->next; if(tmp->next==NULL){ tmp->next = leave; break; } tmp2 = leave->next; leave->next = tmp->next; tmp->next = leave; leave = tmp2; } return ret; } }; // int main() { ListNode n1(3),n2(5),n3(2),n4(8),n5(6),n6(0),n7(4); n1.next=&n2; n2.next=&n3; n3.next=&n4; n4.next=&n5; n6.next=&n7; n5.next=&n6; Solution sol; ListNode * ret = sol.sortList(&n1); ListNode * p = ret; while(p!=NULL){ cout<<p->val<<" "; p = p->next; } cout<<endl; return 0; }
标签:
原文地址:http://www.cnblogs.com/Azhu/p/4353413.html