leetcode-sort list
来源:互联网 发布:windows服务 编辑:程序博客网 时间:2024/05/22 13:21
Sort a linked list in O(n log n) time using constant space complexity.
思路:
归并排序:找到链表的中间结点,对两个已有序链表进行合并。
代码:
ListNode* mergeList(ListNode *p, ListNode *q)
{
ListNode head(0);
ListNode *cur=&head;
while(p!=NULL && q!=NULL)
{
if(p->val<=q->val)
{
cur->next=p;
p=p->next;
}
else
{
cur->next=q;
q=q->next;
}
cur=cur->next;
}
cur->next=p!=NULL?p:q;
return head.next;
}
ListNode *sortList(ListNode *head)
{
if(head==NULL || head->next==NULL)
return head;
ListNode *p=head;
ListNode *q=head;
while(p->next!=NULL && q->next->next!=NULL)
{
p=p->next;
q=q->next;
}
ListNode *midNext=p->next;
p->next=NULL;
return mergeList(sortList(head),sortList(midNext));
}
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
- Socket长连接与短连接
- grails保存mysql乱码
- 设计模式之中介者模式
- oracle Result Set Caching
- 接口的概念
- leetcode-sort list
- 关于微信支付
- 终端运用程序名关闭正在运行的程序
- 索引的删除和更新
- Boost学习之指针容器--pointer_container
- 深入理解Apache Mina (3)---- 与IoHandler相关的几个类
- Jenkins+Ant+Jmeter搭建持续集成的接口测试平台
- APP漏洞导致移动支付隐患重重,未来之路如何走?
- 深入理解Apache Mina (4)---- IoFilter和IoHandler的区别和联系