数据结构实验之链表四:有序链表的归并
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
分别输入两个有序的整数序列(分别包含M和N个数据),建立两个有序的单链表,将这两个有序单链表合并成为一个大的有序单链表,并依次输出合并后的单链表数据。
Input
第一行输入M与N的值;
第二行依次输入M个有序的整数;
第三行依次输入N个有序的整数。
Output
输出合并后的单链表所包含的M+N个有序的整数。
Sample Input
6 5
1 23 26 45 66 99
14 21 28 50 100
Sample Output
1 14 21 23 26 28 45 50 66 99 100
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
} s;//链表是把结点连接起来,首先建立链表的结点,里面存放数据域和指针域
struct node *creat(int n)
{
int i;
struct node *head,*p,*tail;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head;//申请一个头节点让它为空,让尾指针指向
for(i=1; i<=n; i++)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;//p现在是一个存放了数据和指针的结点
tail->next=p;//要把p连接在链表中就要把p连接在尾结点之后,要连接尾结点和p,如果想要把尾结点和p连接在一起,那就要把p的地址记下来,用tail记p的地址,就是tail->next=p,这样就把p的地址记下来了,
tail=p; //连接起新的链表之后,就需要把尾结点放在最后,tail=p
}
return head;
};
struct node *plus(struct node *head1,struct node *head2)
{
struct node *p,*q,*tail;
p=head1->next;
q=head2->next;
tail=head1;//用尾指针连接链表
while(p&&q)//如果两个指针都不为空
{
if(p->data<=q->data)//顺序排列
{
tail->next=p;
tail=p;
p=p->next;//如果这个结点符合要求,连接,并且指向下一个结点
}
else
{
tail->next=q;
tail=q;
q=q->next;//如果这个结点符合要求,连接,并且指向下一个结点
}
}
if(p)//如果没有指到最后一个尾指针指向它
{
tail->next=p;
}
if(q)//如果没有指到最后一个尾指针指向它
{
tail->next=q;
}
return head1;
}
void print(struct node *head)
{
int n=0;
struct node *p;
p=head->next;
while(p)//只要p不为空
{
n++;
if(n==1)
printf("%d",p->data);
else
printf(" %d",p->data);//输出p所保存的数据,输出结束后指向下一个
p=p->next;
}
printf("\n");//n保证空格数量完全一致
}
int main()
{
int m,n;
scanf("%d %d",&m,&n);
struct node *h1,*h,*h2;
h1=creat(m);
h2=creat(n);
h=plus(h1,h2);
print(h);
return 0;
}