实验二
归并顺序表。
• 请按以下要求编程实现:
• 从键盘输入两个升序排列的整数序列linka和linkb,每个序列以输入0为结束标记。
• 将链表linka和linkb归并为linkc,linkc仍然为升序排列。归并完成后,linka和linkb为空表。输出linkc。
• 对linkc进行处理,保持升序不变,删除其中重复的整数,对重复的整数只保留一个,输出删除重复整数后的链表。
实现代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct linka
{
int data;
struct linka* next;
};
struct linkb
{
int data;
struct linkb* next;
};
struct linkc
{
int data;
struct linkc* next;
};
struct linka *p1,*q1,*head1;
struct linkb *p2,*q2,*head2;
struct linkc *p3,*q3,*head3;
int main()
{
int in1;
head1=(struct linka*)malloc(sizeof(struct linka));//表A的头结点
head2=(struct linkb*)malloc(sizeof(struct linkb));//表B的头结点
head3=(struct linkc*)malloc(sizeof(struct linkc));//表C的头结点
head1->data=0,head1->next=NULL;//表A头结点的初始化
head2->data=0,head2->next=NULL;//表B头结点的初始化
head3->data=0,head3->next=NULL;//表C头结点的初始化
q1=head1,q2=head2,q3=head3;
scanf("%d",&in1);
while(in1!=0)
{
p1=(struct linka*)malloc(sizeof(struct linka));
q1->next=p1;
p1->data=in1;
p1->next=NULL;
q1=q1->next;
scanf("%d",&in1);
}//给链表A输入数
scanf("%d",&in1);
while(in1!=0)
{
p2=(struct linkb*)malloc(sizeof(struct linkb));
q2->next=p2;
p2->data=in1;
p2->next=NULL;
q2=q2->next;
scanf("%d",&in1);
}//给链表B输入数
p1=head1;
p2=head2;
p1=p1->next;
p2=p2->next;
while(p1!=NULL&&p2!=NULL)
{
if(p1->data>p2->data)
{
p3=(struct linkc*)malloc(sizeof(struct linkc));
q3->next=p3;
p3->data=p2->data;
p3->next=NULL;
q3=q3->next;
p2=p2->next;
}
else if(p1->data<p2->data)
{
p3=(struct linkc*)malloc(sizeof(struct linkc));
q3->next=p3;
p3->data=p1->data;
p3->next=NULL;
q3=q3->next;
p1=p1->next;
}
else if(p1->data==p2->data)
{
p3=(struct linkc*)malloc(sizeof(struct linkc));
q3->next=p3;
p3->data=p2->data;
p3->next=NULL;
q3=q3->next;
p1=p1->next;
p2=p2->next;
}
}
if(p1==NULL)
{
while(p2!=NULL)
{
if(p2->data!=p3->data)
{
p3=(struct linkc*)malloc(sizeof(struct linkc));
q3->next=p3;
p3->data=p2->data;
p3->next=NULL;
q3=q3->next;
p2=p2->next;
}
else
{
p2=p2->next;
}
}
}
else if(p2==NULL)
{
while(p1!=NULL)
{
if(p1->data!=p3->data)
{
p3=(struct linkc*)malloc(sizeof(struct linkc));
q3->next=p3;
p3->data=p1->data;
p3->next=NULL;
q3=q3->next;
p1=p1->next;
}
else
{
p1=p1->next;
}
}
}
p3=head3;
while(p3->next!=NULL)
{
p3=p3->next;
printf("%d ",p3->data);
}
}