Leetcode Sort List 解题报告
2014-08-15 02:01
309 查看
这道题用 mergesort,linkedlist的mergesort可以达到O(1) 的空间复杂度,而array就很难做到。mergesort是个递归算法,在每一步,需要把当前的linkedlist均分成两段,分别sort,然后merge。均分的过程容易出错。快指针(fast)需要先“走两步”,否则,如果linkedlist如果只有两个节点,那么将陷入死循环。
merge的过程中有的解法加入一个dummy node,这样merge的过程非常简单,只需要不断地扩展dummy node开头的链表即可。但是这样做的结果是空间复杂度不再是O(1)了。
merge的过程中有的解法加入一个dummy node,这样merge的过程非常简单,只需要不断地扩展dummy node开头的链表即可。但是这样做的结果是空间复杂度不再是O(1)了。
#include <iostream> using namespace std; /** * Definition for singly-linked list. */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; void printList(ListNode *head) { while (head) { cout<<head->val<<"\t"; head = head->next; } cout<<endl; } class Solution { public: ListNode* merge(ListNode *h1, ListNode *h2) { ListNode *head = h1; ListNode *n1, *n2, *p1 = NULL; while (h1 && h2) { n1 = h1->next; n2 = h2->next; if (h1->val < h2->val) { p1 = h1; h1 = n1; } else { if (p1 != NULL) { p1->next = h2; } else { head = h2; } h2->next = h1; p1 = h2; h2 = n2; } } if (p1 == NULL) { return h2; } while (h2) { p1->next = h2; p1 = h2; h2 = h2->next; } return head; } ListNode *sortList(ListNode *head) { // cout<<"debug:"; // printList(head); if (head == NULL || head->next == NULL) { return head; } ListNode *slow = head, *fast = head->next->next; while (fast != NULL) { slow = slow->next; fast = fast->next; if (fast) { fast = fast->next; } } ListNode *p = slow->next; slow->next = NULL; head = sortList(head); p = sortList(p); return merge(head, p); } }; int main() { ListNode *head = new ListNode(1); head->next = new ListNode(3); head->next->next = new ListNode(5); head->next->next->next = new ListNode(5); cout<<"before: "; printList(head); Solution s; head = s.sortList(head); cout<<"after: "; printList(head); }
相关文章推荐
- LeetCode Sort List 解题报告
- LeetCode 148. Sort List 解题报告(归并排序小结)
- 【LeetCode】Insertion Sort List 解题报告
- [leetcode] 147. Insertion Sort List 解题报告
- Leetcode Insertion Sort List 解题报告
- Leetcode Insertion Sort List 解题报告
- leetCode解题报告之Sort List
- LeetCode—Sort List解题报告
- [LeetCode]Sort List,解题报告
- leetcode 148. Sort List 解题报告
- LeetCode: Sort List 解题报告
- LeetCode—Insertion Sort List 解题报告
- [Leetcode] 147. Insertion Sort List 解题报告
- [leetcode] 148. Sort List 解题报告
- leetCode解题报告之Insertion Sort List
- LeetCode解题报告—— Rotate List & Set Matrix Zeroes & Sort Colors
- [Leetcode] 148. Sort List 解题报告
- LeetCode: Insertion Sort List 解题报告
- LeetCode Sort List 解题报告
- 景岁的Leetcode解题报告:147.Insertion Sort List (Java)