题目:输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的。
#include<iostream>
using namespace std;
struct ListNode
{
int value;
ListNode* next;
};
typedef struct ListNode L;
L* merge_list(L* p_head1,L* p_head2)
{
L* p_head=NULL;
if(p_head1==NULL){
p_head=p_head2;
}else if(p_head2==NULL){
p_head=p_head1;
}else{
if(p_head1->value < p_head2->value){
p_head=p_head1;
p_head->next=merge_list(p_head1->next,p_head2);
}else if(p_head1->value > p_head2->value){
p_head=p_head2;
p_head->next=merge_list(p_head1,p_head2->next);
}else{
p_head=p_head1;
p_head->next=merge_list(p_head1->next,p_head2->next);
}
}
return p_head;
}
L* create(int value,L* next=NULL)
{
L* l=new L;
l->value=value;
l->next=next;
return l;
}
void print_list(L* p_head)
{
L* l=p_head;
while(l!=NULL){
cout<<l->value<<ends;
l=l->next;
}
cout<<endl;
}
int main()
{
L* g=create(7);
L* e=create(5,g);
L* c=create(3,e);
L* a=create(1,c);
print_list(a);
L* h=create(8);
L* f=create(6,h);
L* d=create(4,f);
L* b=create(2,d);
print_list(b);
L* p_head=merge_list(a,b);
print_list(p_head);
return 0;
}