Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
合并两个有序链表,这道题比较简单吧。
C++版本
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
ListNode *L,*p,*q;
//L=(ListNode*)malloc(sizeof(ListNode));
L=NULL;
p=L;
while(l1||l2)
{
if(l2==NULL||(l1!=NULL&&l1->val<l2->val))
{
q=(ListNode*)malloc(sizeof(ListNode));
q->val=l1->val;
q->next=NULL;
if(L==NULL)
L=q;
else
p->next=q;
p=q;
l1=l1->next;
}
else
{
q=(ListNode*)malloc(sizeof(ListNode));
q->val=l2->val;
q->next=NULL;
if(L==NULL)
L=q;
else
p->next=q;
p=q;
l2=l2->next;
}
}
return L;
}
};
void main()
{
ListNode *L,*p,*q,*L1,*L2;
int N,M,i,temp;
Solution solve;
L1= (ListNode*)malloc(sizeof(ListNode));
L2= (ListNode*)malloc(sizeof(ListNode));
cin>>N;
cin>>M;
L1=NULL;
p=L1;
for(i=0;i<N;i++)
{
cin>>temp;
q= (ListNode*)malloc(sizeof(ListNode));
q->val=temp;
q->next=NULL;
if(NULL==L1)
L1=q;
else
p->next=q;
p=q;
}
L2=NULL;
p=L2;
for(i=0;i<M;i++)
{
cin>>temp;
q= (ListNode*)malloc(sizeof(ListNode));
q->val=temp;
q->next=NULL;
if(NULL==L2)
L2=q;
else
p->next=q;
p=q;
}
L=solve.mergeTwoLists(L1,L2);
while(L)
{
cout<<L->val<<' ';
L=L->next;
}
}
递归版本
#include<iostream>
using namespace std;
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;
if(l1->val<l2->val)
{
l1->next=mergeTwoLists(l1->next, l2);
return l1;
}
else
{
l2->next=mergeTwoLists(l1, l2->next);
return l2;
}
}
};
void main()
{
ListNode *L,*p,*q,*L1,*L2;
int N,M,i,temp;
Solution solve;
L1= (ListNode*)malloc(sizeof(ListNode));
L2= (ListNode*)malloc(sizeof(ListNode));
cin>>N;
cin>>M;
L1=NULL;
p=L1;
for(i=0;i<N;i++)
{
cin>>temp;
q= (ListNode*)malloc(sizeof(ListNode));
q->val=temp;
q->next=NULL;
if(NULL==L1)
L1=q;
else
p->next=q;
p=q;
}
L2=NULL;
p=L2;
for(i=0;i<M;i++)
{
cin>>temp;
q= (ListNode*)malloc(sizeof(ListNode));
q->val=temp;
q->next=NULL;
if(NULL==L2)
L2=q;
else
p->next=q;
p=q;
}
L=solve.mergeTwoLists(L1,L2);
while(L)
{
cout<<L->val<<' ';
L=L->next;
}
}