您的位置:首页 > 其它

单链表上的操作

2013-07-28 00:00 134 查看
题:假设有两个按元素值递增有序的线性表A 和B,均以单链表作存储结
构,试编写算法将A 表和B 表归并成一个按元素值递减有序的线性表
C,并要求利用原表的空间存放C。

#include <iostream>
#define M 3
#define N 2
using namespace std;
struct Link{
int x;
struct Link *next;
};
void main(){
//Creating two links;
struct Link *Ahead=new Link,*Ar=Ahead;
Ahead->next=NULL;
struct Link *Bhead=new Link,*Br=Bhead;
Bhead->next=NULL;
//Creating M nodes of link A;
cout<<"Input "<<M<<" number(s)  which must be inputted in ascending order (link A):";
for(int i=0;i<M;i++){
struct Link *p=new Link;//Creating a new node;
cin>>p->x;
p->next=NULL;
Ar->next=p;//Letting the last node's next point to the newly-created node;
Ar=p;//*p has become the last node and let r point to it.Remember,r always points to the last node;
}
//Creating N nodes of link B;
cout<<"Input "<<N <<" number(s)  which must be inputted in ascending order (link B):";
for(i=0;i<N ;i++){
struct Link *p=new Link;//Creating a new node;
cin>>p->x;
p->next=NULL;
Br->next=p;//Letting the last node's next point to the newly-created node;
Br=p;//*p has become the last node and let r point to it.Remember,r always points to the last node;
}
//Combining A with B to get C which should be in descend order;
Ar=Ahead->next;
Br=Bhead->next;
struct Link *Chead=new Link,*Cr;//Creating a new head node;
Chead->next=NULL;
while(Ar&&Br){
if(Ar->x<=Br->x) {
struct Link *Ap=Ar;
Ar=Ar->next;//Reserving the link;
Ap->next=Chead->next;//Insert
Chead->next=Ap;
}
else{
struct Link *Bp=Br;
Br=Br->next;//Reserving the link;
Bp->next=Chead->next;//Insert
Chead->next=Bp;
}
}
//Inserting the remain nodes;
struct Link *r=Ar?Ar:Br;//Let r point to the point which is not NULL;
if(r){//Ensure r is not NULL;
struct Link *s=r->next;//Reserving the link;
while(s){//not only one node;
//Insert
r->next=Chead->next;
Chead->next=r;//cout<<r->next->x<<endl;
r=s;//pointing to the next node;
s=s->next;
}
//insert the last node;
r->next=Chead->next;
Chead->next=r;cout<<r->next->x<<endl;
}
//Show these elements in the link;
Cr=Chead->next;
while(Cr){
cout<<Cr->x<<" ";
Cr=Cr->next;
}
cout<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: