将线性表la和lb合并为lc【link_la+lb=lc】
#include <iostream.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}lnode; //链表结点定义
#ifndef NULL
const int NULL=0;
#endif // 定义NULL常量
lnode * buildlink(int leng,lnode *p);
void output(lnode * p);
lnode* merge(lnode *la,lnode *lb,lnode *lc);
void main(void)
{
lnode *la,*lb,*lc;
int n,m;
cout<<"input the length of the la and lb:";
cin>>n>>m;
cout<<'\n';
la=(lnode *)malloc(sizeof(lnode));
if(la==NULL)
cout<<"la memory has not accessed ! false";//测试头节点空间是否成功
lb=(lnode *)malloc(sizeof(lnode));
if(lb==NULL)
cout<<"lb memory has not accessed ! false";
la->data=n;
la->next=NULL;
lb->data=n;
lb->next=NULL;
lc=(lnode *)malloc(sizeof(lnode));
if(lc==NULL)
cout<<"lc memory has not accessed ! false";
lc->next=NULL;
cout<<"la:"<<endl;
la=buildlink(n,la); //建立链表
cout<<"lb:"<<endl;
lb=buildlink(m,lb);
lc=merge(la,lb,lc); //合并链表
output(lc); //输出链表
}
#include <iostream.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}lnode; //链表结点定义
#ifndef NULL
const int NULL=0;
#endif // 定义NULL常量
lnode * buildlink(int leng,lnode *p);
void output(lnode * p);
lnode* merge(lnode *la,lnode *lb,lnode *lc);
void main(void)
{
lnode *la,*lb,*lc;
int n,m;
cout<<"input the length of the la and lb:";
cin>>n>>m;
cout<<'\n';
la=(lnode *)malloc(sizeof(lnode));
if(la==NULL)
cout<<"la memory has not accessed ! false";//测试头节点空间是否成功
lb=(lnode *)malloc(sizeof(lnode));
if(lb==NULL)
cout<<"lb memory has not accessed ! false";
la->data=n;
la->next=NULL;
lb->data=n;
lb->next=NULL;
lc=(lnode *)malloc(sizeof(lnode));
if(lc==NULL)
cout<<"lc memory has not accessed ! false";
lc->next=NULL;
cout<<"la:"<<endl;
la=buildlink(n,la); //建立链表
cout<<"lb:"<<endl;
lb=buildlink(m,lb);
lc=merge(la,lb,lc); //合并链表
output(lc); //输出链表
}
lnode* buildlink(int leng,lnode *p)
{
lnode *h;
int i=1;
h=p;
while(i<=leng)
{
lnode *s;
s=(lnode *)malloc(sizeof(lnode));
s->next=NULL;
// cout<<"input the "<<i<<"th data:"<<ends;
cin>>s->data;
h->next=s;
h=s;
i++;
}
return(p);
}
{
lnode *h;
int i=1;
h=p;
while(i<=leng)
{
lnode *s;
s=(lnode *)malloc(sizeof(lnode));
s->next=NULL;
// cout<<"input the "<<i<<"th data:"<<ends;
cin>>s->data;
h->next=s;
h=s;
i++;
}
return(p);
}
lnode* merge(lnode *la,lnode *lb,lnode *lc)
{
lnode *p,*q,*r;
p=la->next;
q=lb->next;
r=lc;
while((p!=NULL)&&(q!=NULL))
{
if (p->data>q->data)
{ r->next=q;
q=q->next;
r=r->next;
r->next=NULL;
}
else if (p->data<q->data)
{ r->next=p;
p=p->next;
r=r->next;
r->next=NULL;
}
else
{ r->next=p;
p=p->next;
q=q->next;
r=r->next;
r->next=NULL;
}
}
if(p!=NULL) r->next=p;
if (q!=NULL) r->next=q;
return(lc);
}
void output(lnode * p)
{
lnode *h;
cout<<"output the linear_link datas :"<<endl;
h=p->next;
while(h)
{
cout<<h<<":"<<h->data<<endl;
h=h->next;
}
}
{
lnode *h;
cout<<"output the linear_link datas :"<<endl;
h=p->next;
while(h)
{
cout<<h<<":"<<h->data<<endl;
h=h->next;
}
}
转载于:https://blog.51cto.com/simeixiaofeng/182093