Leetcode Sort List
来源:互联网 发布:cocos2d js 教程 mac 编辑:程序博客网 时间:2024/05/08 22:13
题意:将链表排序。
思路:使用归并排序。
/** * 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; }};
0 0
- [leetcode][list][sort] Sort List
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Leetcode: Insertion Sort List
- Leetcode: Sort List
- Sort List | leetcode
- leetcode-Sort List
- leetcode-Insertion Sort List
- LeetCode题解:Sort List
- leetcode 134: Sort List
- [LeetCode]Sort List
- [LeetCode]Insertion Sort List
- [LeetCode] Sort List
- 【LeetCode】Insertion Sort List
- leetCode - Sort List
- LeetCode | Insertion Sort List
- LeetCode - Insertion Sort List
- 程序员必备基础知识:通信协议——Http、TCP、UDP
- EMC FC AX-4存储崩溃,raid5硬盘损坏
- “暴风一号”学习日记(一)
- oracle删除数据后回收磁盘空间
- NET面试题
- Leetcode Sort List
- Volley详解之自定义volley请求
- linux make命令
- Java线程池详解(一)
- ubuntu开发环境搭建----dm365
- Android开发环境搭建
- 直播技术资料整理
- IBM服务器raid5崩溃数据恢复方法
- Python练习实例11