编写一个函数实现两个按升序排列的顺序表的合并操作,要用C语言编写,能在程序上运行的,C的初学者,谢谢

如题所述

第1个回答  2010-10-10
注释的部分是采用数组实现的,未注释的是采用链表实现的,可以将链表实现的注释起来和数组实现的运行做对比

#include "stdio.h"
#include "stdlib.h"
/*采用数组实现
int merge(int* a,int* b,int*c,int alen,int blen)
{
int i=0,j=0,k=0;
//每次将a和b中当前的元素进行比较,并将小的一个存入到c中
while(i<alen && j<blen)
{
if(a[i]<b[j])
c[k]=a[i++];
else c[k]=b[j++];
k++;
}
//其中一个数组已经结束,将另一个数组剩余部分全部复制到c即可
while(i<alen)
c[k++]=a[i++];
while(j<blen)
c[k++]=b[j++];
return k;//返回值为c的有效长度
}
void main()
{
int a[]={1,3,5,7,9,10,12,14};
int b[]={2,4,6,8,10,11,12,13};
int c[100];
int i,clen;
clen=merge(a,b,c,sizeof(a)/sizeof(*a),sizeof(b)/sizeof(*b));
for(i=0;i<clen;i++)
printf("%d ",c[i]);
printf("\n");
}
*/
struct Node
{
int value;
struct Node* next;
};
struct LinkList
{
struct Node* head;
};
//将数组a赋值给链表list
void setLinkList(int* a,int alen,struct LinkList* list)
{
int i;
struct Node* p,*temp;
list->head=(struct Node*)malloc(sizeof(struct Node));
p=list->head;
for(i=0;i<alen;i++)
{
p->value=a[i];
p->next=(struct Node*)malloc(sizeof(struct Node));
temp=p;
p=p->next;
}
free(p);
temp->next=NULL;//尾指针赋NULL
}
void mergeLinkList(struct LinkList* a,struct LinkList* b,struct LinkList* c)
{
struct Node *p=a->head,*q=b->head,*r,*temp;
c->head=(struct Node*)malloc(sizeof(struct Node));
r=c->head;
while(p!=NULL && q!=NULL)
{
if(p->value<q->value)
{
r->value=p->value;
p=p->next;
}
else
{
r->value=q->value;
q=q->next;
}
r->next=(struct Node*)malloc(sizeof(struct Node));
temp=r;
r=r->next;
}
while(p!=NULL)
{
r->value=p->value;
p=p->next;
r->next=(struct Node*)malloc(sizeof(struct Node));
temp=r;
r=r->next;
}
while(q!=NULL)
{
r->value=q->value;
q=q->next;
r->next=(struct Node*)malloc(sizeof(struct Node));
temp=r;
r=r->next;
}
free(r);
temp->next=NULL;
}
#define MAX_LEN 1000
void main()
{
int a[MAX_LEN];//={1,3,5,7,9,10,12,14};
int b[MAX_LEN];//={2,4,6,8,10,11,12,13};
int alen,blen,i;
struct LinkList alist,blist,clist;
struct Node* p;

printf("Please input the length of a : ");
scanf("%d",&alen);
fflush(stdin);
printf("Please input %d number and separate them with space :\n",alen);
for(i=0;i<alen;i++)
scanf("%d",a+i);
fflush(stdin);//这句很有必要,当输入的数据超过alen时,后面的数据将被忽略

printf("Please input the length of b : ");
scanf("%d",&blen);
fflush(stdin);
printf("Please input %d number and separate them with space :\n",blen);
for(i=0;i<blen;i++)
scanf("%d",b+i);
fflush(stdin);

setLinkList(a,alen,&alist);
setLinkList(b,blen,&blist);
mergeLinkList(&alist,&blist,&clist);
p=clist.head;
printf("The result is :\n");
while(p!=NULL)
{
printf("%d ",p->value);
p=p->next;
}
printf("\n");
}本回答被提问者采纳
相似回答