合并两个排序的链表
- 参与人数:1527时间限制:1秒空间限制:32768K
- 通过比例:27.96%
- 最佳记录:0 ms|8552K(来自 牛客708854号)
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
好久没碰指针和链表了,先从基础题刷起。(面试题也有很多链表的操作,包括程序改错也是有指针的)
持续更新中。
#include<stdio.h>
#include<iostream>
using namespace std;
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) return pHead2;
else if(!pHead2) return pHead1;
ListNode *p,*q;
p=new ListNode(NULL);
q=p;
while(pHead1||pHead2)
{
if(!pHead1&&pHead2)
{
p->next=pHead2;
p=pHead2;
break;
}
if(!pHead2&&pHead1)
{
p->next=pHead1;
p=pHead1;
break;
}
if(pHead1->val<pHead2->val)
{
p->next=pHead1;
p=pHead1;
pHead1=pHead1->next;
}
else
{
p->next=pHead2;
p=pHead2;
pHead2=pHead2->next;
}
}
return q->next;
}
ListNode* CreatList(ListNode *pHead,int n)
{
if(n==0) return NULL;
ListNode *p,*q;
pHead=new ListNode(NULL);
p=pHead;
cin>>p->val;
int x;
while(--n)
{
cin>>x;
q=new ListNode(x);
p->next=q;
p=q;
}
return pHead;
}
};
int main()
{
int n,m;
Solution so;
ListNode *L1,*L2;
cin>>n;
L1=so.CreatList(L1,n);
cin>>m;
L2=so.CreatList(L2,m);
ListNode *ans=so.Merge(L1,L2);
while(ans)
{
printf("%d\t",ans->val);
ans=ans->next;
}
return 0;
}