//定义两个同种单向链表,包含一个整数值和一个指向本节点的类型的指针,该链表中的数据都已经排好序
//编制程序,合并两个链表
#include<iostream.h>
#include<iomanip.h>
struct Node
{
int key;
Node *next;
};
void Create(Node *&);
void Print(Node *);
Node *Compare(Node *,Node *); //合并
int main()
{
Node *list1,*list2,*head;
Create(list1);
cout<<"The list1 is:\n";
Print(list1);
Create(list2);
cout<<"The list2 is:\n";
Print(list2);
cout<<"Compare the link is:\n";
head=Compare(list1,list2);
Print(head);
return 0;
}
void Create(Node *&head) //接受引用,形参head就是指向实参的那个变量的别名
{
Node *pb,*pend;
head=NULL;
pb=pend=new Node;
cout<<"Please input value(input 0 is over!):\n";
cin>>pb->key;
while(pb->key!=0)
{
if(head==NULL)
head=pb;
else
pend->next=pb;
pend=pb;
pb=new Node;
cin>>pb->key;
}
pend->next=NULL;
delete pb;
}
void Print(Node *head)
{
while(head)
{
if(head->next==NULL)
cout<<head->key<<endl;
else
cout<<head->key<<"->";
head=head->next;
}
}
Node *Compare(Node *list1,Node *list2)
{
Node *newhead;
if(list1->key<=list2->key) //设置新的头结点
newhead=list1;
else
newhead=list2;
Node *prev1,*prev2;
prev1=list1;
prev2=list2;
while(list1 && list2) //遍历两条链表开始合并
{
if(prev1->key<=prev2->key)
{
if(prev1->next==NULL)//是最后一个节点时终止循环
break;
list1=prev1->next; //预存下一个节点
if(prev1->next->key>prev2->key)
prev1->next=prev2; //将两个节点联系起来
prev1=list1; //移动节点
}
else
{
if(prev2->next==NULL)
break;
list2=prev2->next;
if(prev2->next->key>prev1->key)
prev2->next=prev1;
prev2=list2; //移动节点
}
}
if(list1==NULL) //list1链表比较短时
prev1->next=prev2;
else
prev2->next=prev1;
return newhead;
//编制程序,合并两个链表
#include<iostream.h>
#include<iomanip.h>
struct Node
{
int key;
Node *next;
};
void Create(Node *&);
void Print(Node *);
Node *Compare(Node *,Node *); //合并
int main()
{
Node *list1,*list2,*head;
Create(list1);
cout<<"The list1 is:\n";
Print(list1);
Create(list2);
cout<<"The list2 is:\n";
Print(list2);
cout<<"Compare the link is:\n";
head=Compare(list1,list2);
Print(head);
return 0;
}
void Create(Node *&head) //接受引用,形参head就是指向实参的那个变量的别名
{
Node *pb,*pend;
head=NULL;
pb=pend=new Node;
cout<<"Please input value(input 0 is over!):\n";
cin>>pb->key;
while(pb->key!=0)
{
if(head==NULL)
head=pb;
else
pend->next=pb;
pend=pb;
pb=new Node;
cin>>pb->key;
}
pend->next=NULL;
delete pb;
}
void Print(Node *head)
{
while(head)
{
if(head->next==NULL)
cout<<head->key<<endl;
else
cout<<head->key<<"->";
head=head->next;
}
}
Node *Compare(Node *list1,Node *list2)
{
Node *newhead;
if(list1->key<=list2->key) //设置新的头结点
newhead=list1;
else
newhead=list2;
Node *prev1,*prev2;
prev1=list1;
prev2=list2;
while(list1 && list2) //遍历两条链表开始合并
{
if(prev1->key<=prev2->key)
{
if(prev1->next==NULL)//是最后一个节点时终止循环
break;
list1=prev1->next; //预存下一个节点
if(prev1->next->key>prev2->key)
prev1->next=prev2; //将两个节点联系起来
prev1=list1; //移动节点
}
else
{
if(prev2->next==NULL)
break;
list2=prev2->next;
if(prev2->next->key>prev1->key)
prev2->next=prev1;
prev2=list2; //移动节点
}
}
if(list1==NULL) //list1链表比较短时
prev1->next=prev2;
else
prev2->next=prev1;
return newhead;
}
转自:http://blog.csdn.net/gxwzmm/article/details/8578438