题意:将链表排序。
思路:使用归并排序。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<ListNode*> mylist;
ListNode* sortList(ListNode* head) {
if(head == NULL) return head;
ListNode* next = head;
while(next) {
mylist.push_back(next);
next = next->next;
}
next = mysort(0, mylist.size() - 1);
return next;
}
ListNode* mysort(int low, int high) {
if(low == high) {
mylist[low]->next = NULL;
return mylist[low];
}
int mid = low + (high - low) / 2;
ListNode* temp1 = mysort(low, mid); //if(temp1) cout << temp1->val << endl;
ListNode* temp2 = mysort(mid + 1, high); //if(temp2) cout << temp2->val << endl;
cout << endl;
ListNode* myhead = new ListNode(0);
ListNode* next = myhead;
while(temp1 || temp2) {
ListNode* tempnext = NULL;
if(temp1 && temp2) {
if(temp1->val < temp2->val) {
tempnext = temp1;
temp1 = temp1->next;
}
else {
tempnext = temp2;
temp2 = temp2->next;
}
next->next = tempnext;
next = tempnext;
continue;
}
if(temp1 && !temp2) {
tempnext = temp1;
temp1 = temp1->next;
next->next = tempnext;
next = tempnext;
continue;
}
if(!temp1 && temp2) {
tempnext = temp2;
temp2 = temp2->next;
next->next = tempnext;
next = tempnext;
continue;
}
}
//next->next = NULL;
//show the list
/*
ListNode* testnext = myhead;
while(testnext) {
cout << testnext->val << " ";
testnext = testnext->next;
}
cout << endl;
*/
next = myhead->next;
delete myhead;
return next;
}
};