合并两个顺序列表c语言,c语言实现两个顺序表的合并

匿名用户

1级

2013-09-24 回答

一个算法给你(假如是升序,并且不重复)

while(表1不结束 && 表2不结束) {

if (表1结束 || 表1.当前值>表2.当前值) {表2.当前值插入新表;表2.当前值向后移动}

else if (表2结束 || 表1.当前值

else if (表1.当前值=表2.当前值) {表1.当前值插入新表;表1.当前值和表2.当前值向后移动}

}

#include

#include

#include

struct student {

int num;

struct student  *next;

};

void print(struct student *head) {

struct student *p;

p=head;

char s=' ';

if(head==NULL) {

printf("该链表为空");

}

if(head!=NULL) {

do {

printf("%c%c%d",s,s,p->num);

p=p->next;

} while(p!=NULL);

printf("\n");

}

}

struct student *creatb() {

struct student *head;

struct student *p1,*p2;

int n=0;

p1=p2=(struct student*)malloc(sizeof(struct student));

scanf("%d",&p1->num);

head=NULL;

while(p1->num!=0) {

n=n+1;

if(n==1)

head=p1;

else

p2->next=p1;

p2=p1;

p1=(struct student*)malloc(sizeof(struct student));

scanf("%d",&p1->num);

}

p2->next=NULL;

return head;

}

int main() {

struct student *head1,*head2,*head3;

head1=NULL;

head2=NULL;

head3=NULL;

printf("请输入单链表La,输入0表示输入结束:\n");

head1=creatb();

printf("输入的链表为:");

print(head1);

printf("请输入单链表Lb,输入0表示输入结束:\n");

head2=creatb();

printf("输入的链表为:");

print(head2);

struct student *a,*b,*c, *tmpNode;

a=head1->next;

b=head2;//

head3=c=head1;

while(a != NULL || b != NULL) {

if(b == NULL || (a != NULL && a->num num)) {

c->next=a;

c=a;

a=a->next;

} else if(a == NULL || (b != NULL && a->num > b->num)) {

c->next=b;

c=b;

b=b->next;

} else if (a != NULL && b != NULL) {

c->next=a;

c=a;

a=a->next;

tmpNode = b;

b = b->next;

free(tmpNode);

}

}

c->next=NULL;

printf("合并后的有序链表为:");

print(head3);

c = head3;

while(c) {

tmpNode = c;

c = c->next;

free(tmpNode);

}

return 0;

}

追问:

不能假设他不重复啊,要考虑他有重复的情况的啊

追答:

我假设的是各自里面没有重复

追问:

这个是顺序表吗?好像是链表啊?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值