sort-list.cpp (997B)
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 using namespace std; 5 6 //Runtime: 172ms Beats: 98.86% 7 //Memory: 53.2MB Beats: 71% 8 9 10 struct ListNode{ 11 int val; 12 ListNode* next; 13 14 15 }; 16 17 18 19 ListNode* sortList(ListNode* head) { 20 vector<int> sorted; 21 ListNode* itr = head; 22 ListNode* itr1 = head; 23 while(itr!= NULL){ 24 sorted.push_back(itr->val); 25 itr=itr->next; 26 } 27 sort(sorted.begin(), sorted.end()); 28 for(int i = 0; i < sorted.size(); ++i){ 29 itr1->val = sorted[i]; 30 itr1 = itr1->next; 31 } 32 33 return head; 34 } 35 36 int main(){ 37 ListNode* l1 = new ListNode; 38 ListNode* ln2 = new ListNode; 39 ListNode* ln3 = new ListNode; 40 ListNode* ln4 = new ListNode; 41 l1->val = 0; 42 ln2->val = 10; 43 ln3->val = 4; 44 ln4->val = -1; 45 l1->next = ln2; 46 ln2->next = ln3; 47 ln3->next = ln4; 48 ListNode* l2 = sortList(l1); 49 while(l2 != NULL){ 50 cout << l2->val << " " ; 51 l2 = l2->next; 52 } 53 cout << endl; 54 }