1 Star 0 Fork 0

xiangxiang/LeetCode-NOTES

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
solution.cpp 1.37 KB
一键复制 编辑 原始数据 按行查看 历史
默然 提交于 7年前 . update all algorithms.
/**
* 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||!head->next)
return head;
return mergeSort(head);
}
ListNode * mergeSort(ListNode *head)
{
if(!head||!head->next) //just one element
return head;
ListNode *p=head, *q=head, *pre=NULL;
while(q&&q->next!=NULL)
{
q=q->next->next;
pre=p;
p=p->next; //divide into two parts
}
pre->next=NULL;
ListNode *lhalf=mergeSort(head);
ListNode *rhalf=mergeSort(p); //recursive
return merge(lhalf, rhalf); //merge
}
ListNode * merge(ListNode *lh, ListNode *rh)
{
ListNode *temp=new ListNode(0);
ListNode *p=temp;
while(lh&&rh)
{
if(lh->val<=rh->val)
{
p->next=lh;
lh=lh->next;
}
else
{
p->next=rh;
rh=rh->next;
}
p=p->next;
}
if(!lh)
p->next=rh;
else
p->next=lh;
p=temp->next;
temp->next=NULL;
delete temp;
return p;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/xiangxiang920/LeetCode-NOTES.git
git@gitee.com:xiangxiang920/LeetCode-NOTES.git
xiangxiang920
LeetCode-NOTES
LeetCode-NOTES
master

搜索帮助