您的位置:首页 > 理论基础 > 数据结构算法

数据结构-用链表函数实现链表的有序合并

2013-08-05 20:27 344 查看
描述

链表的合并操作是链表数据结构对象操作的重要内容,请您写一个程序使用链表函数完成对两个链表的合并操作。

请用如下函数完成上述功能,线性表List的定义如下(强烈建议使用下面的定义和函数结构)

typedef struct LNode

{

Elemtype data;

struct LNode *next;

}LNode,*LinkList;

int MergeList_L(LinkList &La,LinkList &Lb,LinkList &Lc, int (*compare)(ElemType,ElemType))

输入

输入有多组测试数据,每组测试数据包括2行,每个链表用一行表示。

输出

输出合并后链表并按从小到大顺序进行排序和输出其内容。

样例输入

List A = ( 18 40 44 52 53 59 )

List B = ( 15 18 19 25 27 35 48 50 55 )

List A = (  1  7 26 27 29 41 45 47 56 )

List B = (  3 11 13 22 22 33 34 44 46 49 57 )

样例输出

MergeList_L(A, B, C);

List C = ( 15 18 18 19 25 27 35 40 44 48 50 52 53 55 59 )

MergeList_L(A, B, C);

List C = (  1  3  7 11 13 22 22 26 27 29 33 34 41 44 45 46 47 49 56 57 )
#include<iostream>
#include<iomanip>
#include<cstring>
#include<cstdio>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}node,*LinkList;
int create(LinkList &l)
{
char c;
int x=0,f=0,f1=0;
l = new node;
LinkList k = new node;
l->next=k->next=NULL;
while(cin>>c&&c!='('){}
while((c=getchar())!=')'){
if(c>='0'&&c<='9'){x=x*10+(c-'0');f1=1;}
if(c==' '&&f1){
LinkList p = new node;
p->data=x;
p->next=NULL;
k->next=p;
k=p;
x=0;
if(f==0){l->next=k;f=1;}
f1=0;
}
}
}
int input(LinkList l)
{
LinkList p = new node;
p=l->next;
while(p)
{

cout<<setw(3)<<p->data;
p=p->next;
}
}
int MergeList_L(LinkList La,LinkList Lb,LinkList &Lc)
{
int i,j,ai,aj,f=1;
Lc = new node;
LinkList k = new node;LinkList q = new node;LinkList p = new node;
q=La->next;
p=Lb->next;
Lc->next=k->next=NULL;
while(p&&q){
if(q->data<=p->data)
{
LinkList kk = new node;
kk->data=q->data;
kk->next=NULL;
k->next=kk;
k=kk;
if(f){Lc->next=k;f=0;}
q=q->next;
}
else
{
LinkList kk = new node;
kk->data=p->data;
kk->next=NULL;
k->next=kk;
k=kk;
if(f){Lc->next=k;f=0;}
p=p->next;

}
}
while(p)
{
LinkList kk = new node;
kk->data=p->data;
kk->next=NULL;
k->next=kk;
k=kk;
if(f){Lc->next=k;f=0;}
p=p->next;
}
while(q)
{
LinkList kk = new node;
kk->data=q->data;
kk->next=NULL;
k->next=kk;
k=kk;
if(f){Lc->next=k;f=0;}
q=q->next;
}

}
int main()
{
char a[5];
LinkList la,lb,lc;
while(cin>>a)
{
create(la);
create(lb);
MergeList_L(la,lb,lc);
// input(la);
cout<<"MergeList_L(A, B, C);"<<endl;
cout<<"List C = (";
input(lc);cout<<" )"<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐