leetcode No148. Sort List
2016-10-26 21:22
316 查看
Question:
Sort a linked list in O(n log n)time using constant space complexity.
Algorithm:
类似归并排序,程序有注释Accepted Code:
/** * 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* pre=head; //第一段的结尾 ListNode* p1=head; //p1一次移动1个结点 ListNode* p2=head; //p2一次移动2个结点 //目标是分成head-pre,p1-p2两段 while(p2!=NULL && p2->next!=NULL){ pre=p1; p1=p1->next; p2=p2->next->next; } pre->next=NULL; //head-pre ListNode* h1=sortList(head); ListNode* h2=sortList(p1); return Merge(h1,h2); } ListNode* Merge(ListNode* l1,ListNode* l2){ if(l1==NULL) return l2; if(l2==NULL) return l1; if(l1->val < l2->val){ l1->next=Merge(l1->next,l2); return l1; } else{ l2->next=Merge(l1,l2->next); return l2; } return NULL; } };
相关文章推荐
- LeetCode 148.Sort List 链表排序
- LeetCode 148. Sort List(链表排序)
- LeetCode 148. Sort List
- **Leetcode 148. Sort List
- LeetCode 148. Sort List 单链表排序 Python Solution
- [LeetCode] 148. Sort List (Linked List) - Using Quick Sort(小改动)
- [LeetCode]problem 148. Sort List
- [leetcode] 148.Sort List
- leetcode_效率题解_148. Sort List_(链表归并排序)
- [LeetCode] 148. Sort List 链表排序
- 【LeetCode】148. Sort List
- leetcode 148. Sort List
- LeetCode 148. Sort List(C++版)
- leetcode 148. Sort List 链表归并排序
- Leetcode-148. Sort List
- Leetcode 148. Sort List
- [Leetcode] 148. Sort List 解题报告
- leetcode 148. Sort List 链表 归并排序 和 快排
- [LeetCode] 148. Sort List 解题思路
- 【leetcode】148. Sort List