匿名用户
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;
}
追问:
不能假设他不重复啊,要考虑他有重复的情况的啊
追答:
我假设的是各自里面没有重复
追问:
这个是顺序表吗?好像是链表啊?