C++实现两个已经排序的链表进行合并

//定义两个同种单向链表,包含一个整数值和一个指向本节点的类型的指针,该链表中的数据都已经排好序
//编制程序,合并两个链表
#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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值