题目:输入两个递增的排序链表,合并者两个链表中的结点仍然是按照递增排序。
#include "iostream"
#include "stdlib.h"
using namespace std;
typedef struct Node{
int value;
struct Node* next;
}Node;
Node* create_list()
{
int data;
Node* head =NULL,*cur;
cin>>data;
while (data !=-1)
{
Node* pNode =(Node*)malloc(sizeof(Node));
pNode->value =data;
pNode->next =NULL;
if (head==NULL)
{
head =pNode;
cur =pNode;
}
else
{
cur->next =pNode;
cur =cur->next;
}
cin>>data;
}
return head;
}
Node* mergelistRecursive(Node* list1,Node* list2)
{
Node* result;
if (!list1)
{
return list2;
}
if (!list2)
{
return list1;
}
if (list1->value>list2->value)
{
result =list2;
result->next =mergelistRecursive(list1,list2->next);
}
if (list1->value<list2->value)
{
result =list1;
result->next =mergelistRecursive(list1->next,list2);
}
return result;
}
Node* mergerlistNonReursively(Node* head1,Node* head2)
{
Node* result,*p1=head1,*p2=head2;
if (!head1)
{
return head2;
}
if (!head2)
{
return head1;
}
if (p1->value>p2->value)
{
result =p2;
p2 =p2->next;
}
else
{
result =p1;
p1 =p1->next;
}
Node* head =result;
while (p1&&p2)
{
if (p1->value>p2->value)
{
result->next =p2;
p2 =p2->next;
result =result->next;
}
else
{
result->next =p1;
p1 =p1->next;
result =result->next;
}
}
if (p1)
{
result->next =p1;
}
if (p2)
{
result->next =p2;
}
return head;
}
void print(Node* head)
{
Node* cur =head;
while(cur)
{
cout<<cur->value<<" ";
cur =cur->next;
}
cout<<endl;
}
void main()
{
Node* list1,*list2,*list3;
list1 =create_list();
print(list1);
list2 =create_list();
print(list2);
//list3 =mergelistRecursive(list1,list2);
list3 =mergerlistNonReursively(list1,list2);
print(list3);
}