leetcode No148. Sort List
来源:互联网 发布:ecowater 净水器 知乎 编辑:程序博客网 时间:2024/06/06 01:28
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; }};
0 0
- leetcode No148. Sort List
- [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
- 组合数学之稳定婚姻问题
- Nginx+Tomcat搭建高性能负载均衡集群
- 使用百度api根据ip获取位置
- Run matlab in server background
- IDA调试so文件进阶篇
- leetcode No148. Sort List
- hibernate保存报错:a different object with the same identifier value was already associated with the ses
- 有他们在密码更安全
- What's new in Xcode 8
- 聪明的投资者 摘录
- Caffe的卷积原理
- 指纹识别智能手枪
- 计算两个坐标点的距离
- java基础--继承