1. 程式人生 > >C++實現兩個已經排序的連結串列進行合併

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