您的位置:首页 > 编程语言 > C语言/C++

合并两个排序的链表

2017-04-27 11:17 197 查看
题目描述:

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

分析:

可以用递归也可以用循环,用循环就用两个指针,分别指向两个链表,判断所指向的节点的值大小,将小的放到新链表中,指针向后移动。注意不用判断相等的情况,相等的情况,随便移动其中一个就行。

递归:

代码:

/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1==NULL)
return pHead2;
if(pHead2==NULL)
return pHead1;
ListNode* newNode=NULL;
if(pHead1->val<pHead2->val){
newNode=new ListNode(pHead1->val);
newNode->next=Merge(pHead1->next,pHead2);
}
else{
newNode=new ListNode(pHead2->val);
newNode->next=Merge(pHead1,pHead2->next);
}
return newNode;
}
};


循环:为了方便,在一开始,多放了一个结点,最后跳过就行

/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1==NULL)
return pHead2;
if(pHead2==NULL)
return pHead1;
ListNode* p=pHead1;
ListNode* q=pHead2;
ListNode* newList=new ListNode(0);
ListNode* pHeadnew=newList;
while(p!=NULL&&q!=NULL){
if(p->val<q->val){
pHeadnew->next=new ListNode(p->val);
pHeadnew=pHeadnew->next;
p=p->next;
}
else{
pHeadnew->next=new ListNode(q->val);
pHeadnew=pHeadnew->next;
q=q->next;
}
}
if(p==NULL)
pHeadnew->next=q;
if(q==NULL)
pHeadnew->next=p;
return newList->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 剑指offer 链表