LeetCode(M) Sort List
来源:互联网 发布:手机淘宝取消退款申请 编辑:程序博客网 时间:2024/06/05 08:35
Sort a linked list in O(n log n) time using constant space complexity.
根据题目O(nlogn)时间,O(1)空间,选择了归并排序
/** * 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 NULL; if(!head->next) return head; // ListNode*pre=new ListNode(-1); /* pre->next=head; ListNode *fast=pre->next,*slow=pre->next->next; while(slow->next&&slow->next->next){ fast=fast->next; slow=slow->next->next; } fast->next=NULL;*/ ListNode *slow = head, *fast = head, *pre = head; while (fast && fast->next) { pre = slow; slow = slow->next; fast = fast->next->next; } pre->next = NULL; // sortList(fast);sortList(slow); // return merge(fast,slow); // sortList(head);sortList(slow); // return merge(head,slow); return merge(sortList(head), sortList(slow)); } ListNode* merge(ListNode* first,ListNode *second){ ListNode *temp=new ListNode(-1),*p=first,*q=second,*pre; pre=temp; while(p&&q){ if(p->val>q->val) {temp->next=q;q=q->next;} else{temp->next=p;p=p->next;} temp=temp->next; } if(p) temp->next=p;//这里由while改成了if if(q) temp->next=q; return pre->next; } };
打了注释的地方都是错误点
0 0
- LeetCode(M) Sort List
- LeetCode-M-Insertion Sort List
- LintCode:M-Sort List
- [leetcode][list][sort] Sort List
- LeetCode-M-Sort Colors
- 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
- AE的一些基本知识
- C++,类,模板杂谈__Boolan
- 蓝桥杯 ALGO-124数字三角形
- Calendar的add和set方法的运用和区别
- 我的科研生活2017-2-22
- LeetCode(M) Sort List
- SDUT 2781 二分练习
- acm入门练习心得
- Struts2常用标签
- 51nod 贪心入门之三 活动安排问题二
- Trapping Rain Water
- [zz]Xilinx中ise原语的使用
- 一个新的开始
- 排序算法(python实现)