https://leetcode.com/problems/sort-list/
1. Using STL:
//76 ms, 14.1 MB/*** 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) return nullptr;vector<int> treelist;ListNode* curr = head;while(head){treelist.push_back(head->val);head = head->next;}sort(treelist.begin(), treelist.end());ListNode* dummy = new ListNode(INT_MIN);ListNode* newhead = dummy;for(int i=0; i<treelist.size(); i++){newhead->next = new ListNode(treelist[i]);newhead = newhead->next;}return dummy->next;}};
2. Using swap sort:
//1860 ms, 15.7 MB
/**
* 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) return nullptr;
ListNode* dummy = new ListNode(-1);
dummy->next = head;
ListNode* first = dummy->next;
ListNode* second = dummy->next->next;
ListNode* prev = dummy->next;
while(second){
if(second->val < first->val){
if(prev == first){
dummy->next = second;
prev->next = second->next;
second->next = prev;
second = first->next;
first = dummy->next;
} else {
ListNode* tmp = first->next;
dummy->next = second;
first->next = second->next;
second->next = tmp;
prev->next = first;
second = first->next;
first = dummy->next;
prev = prev->next;
}
} else {
prev = prev->next;
second = second->next;
}
}
/*
ListNode* test = dummy->next;
while(test){
cout << test->val << "->";
test = test->next;
}
cout << "NULL" << endl;
*/
first->next = sortList(dummy->next->next);
return first;
}
};
