介绍
输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增序列的。
分析
第一种,是可以通过函数嵌套调用,返回值小的指针。
第二种,是通过循环遍历两个链表。
代码
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
typedef struct ListNode
{
int value;
ListNode* next;
}ListNode;
ListNode* merge(ListNode* pHead1,ListNode* pHead2)
{
ListNode* head=NULL;
if(pHead1==NULL)
return pHead2;
if(pHead2==NULL)
return pHead1;
if(pHead1->value > pHead2->value)
{
head=pHead2;
head->next=merge(pHead1,pHead2->next);
}
else
{
head=pHead1;
head->next=merge(pHead1->next,pHead2);
}
return head;
}
ListNode* merge_second(ListNode* head1,ListNode* head2)
{
ListNode *head=NULL;
ListNode *p_head=(ListNode*)malloc(sizeof(ListNode));
if(head1==NULL&&head2!=NULL)
head=head2;
if(head1!=NULL&&head2==NULL)
head=head1;
if(head1!=NULL&&head2!=NULL)
{
head=p_head;
while(head1!=NULL&&head2!=NULL)
{
if(head1->value > head2->value)
{
p_head->next=head2;
p_head=p_head->next;;
head2=head2->next;
}
else
{
p_head->next=head1;
p_head=p_head->next;
head1=head1->next;
}
}
if(head1==NULL&&head2!=NULL)
p_head->next=head2;
if(head2==NULL&&head1!=NULL)
p_head->next=head1;
}
return head->next;
}
int main()
{
ListNode* a=(ListNode*)malloc(sizeof(ListNode));
a->next=NULL;
a->value=10;
ListNode* b=(ListNode*)malloc(sizeof(ListNode));
b->value=11;
b->next=NULL;
ListNode* a1=a;
for(int i=10;i<20;i+=2)
{
ListNode* m=(ListNode*)malloc(sizeof(ListNode));
m->value=i*2;
m->next=NULL;
a1->next=m;
a1=m;
}
a1=a;
while(a1!=NULL)
{
cout<<a1->value<<" ";
a1=a1->next;
}
cout<<endl;
ListNode* b1=b;
for(int i=9;i<19;i+=2)
{
ListNode* m=(ListNode*)malloc(sizeof(ListNode));
m->value=i*2;
m->next=NULL;
b1->next=m;
b1=m;
}
b1=b;
while(b1!=NULL)
{
cout<<b1->value<<" ";
b1=b1->next;
}
cout<<endl;
ListNode* k=merge(a,b);
while(k!=NULL)
{
cout<<k->value<<" ";
k=k->next;
}
cout<<endl;
/*ListNode* k2=merge_second(a,b);
while(k2!=NULL)
{
cout<<k2->value<<" ";
k2=k2->next;
}*/
system("pause");
return 0;
}
遇到的问题
访问空指针指向的内存时,程序会崩溃。所以要注意空指针问题。两个合并的时间复杂度都是o(n+m)。