Merge Two Sorted Lists
来源:互联网 发布:儿童计算机编程 编辑:程序博客网 时间:2024/05/29 08:17
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
ListNode *p=l1;
ListNode *q=l2;
ListNode *head=NULL;
ListNode *lcode=NULL;
while(p&&q)
{
if(head==NULL)
{
if(p->val<q->val)
{
head=lcode=p;
p=p->next;
lcode->next=NULL;
}
else
{
head=lcode=q;
q=q->next;
lcode->next=NULL;
}
}
else
{
if(p->val<q->val)
{
lcode->next=p;
lcode=p;
p=p->next;
lcode->next=NULL;
//p=p->next;
}
else
{
lcode->next=q;
lcode=q;
q=q->next; //
lcode->next=NULL; //这两行的顺序不能更换
}
}
}
if(p)
{lcode->next=p;
//p=p->next;
}
else if(q)
{
lcode->next=q;
//q=q->next;
}
return head;
}
};
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
ListNode *p=l1;
ListNode *q=l2;
ListNode *head=NULL;
ListNode *lcode=NULL;
while(p&&q)
{
if(head==NULL)
{
if(p->val<q->val)
{
head=lcode=p;
p=p->next;
lcode->next=NULL;
}
else
{
head=lcode=q;
q=q->next;
lcode->next=NULL;
}
}
else
{
if(p->val<q->val)
{
lcode->next=p;
lcode=p;
p=p->next;
lcode->next=NULL;
//p=p->next;
}
else
{
lcode->next=q;
lcode=q;
q=q->next; //
lcode->next=NULL; //这两行的顺序不能更换
}
}
}
if(p)
{lcode->next=p;
//p=p->next;
}
else if(q)
{
lcode->next=q;
//q=q->next;
}
return head;
}
};
0 0
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- 自定义微信菜单
- native-base中icon不能正确显示
- 剑指offer-生产者消费者模型
- 用BigDump工具导入超大MySQL数据库备份文件
- 用python实现快速排序算法
- Merge Two Sorted Lists
- 二分法典型应用(二)最大化最小值 POJ2456 Aggressive cows
- GitHub入门与实践(二)——初始设置Git,以及在GitHub中添加公开密钥
- 【JAVA技术库】分页模糊查询 进阶版
- 容斥原理 && 欧拉函数 && 抽屉原理 总结
- jQuery 选择器整理
- A. Vicious Keyboard
- 运营工具集合
- Bitmap的高效加载和LruCache缓存