18064 链表的有序合并
Description
已知有两个链表a和b,结点类型相同,均包括一个int类型的数据。编程把两个链表合并成一个,结点按升序排列。
#include "stdio.h"
#include "malloc.h"
#define LEN sizeof(struct DATA)
struct DATA
{
long num;
struct DATA *next;
};
struct DATA *create(int n)
{
struct DATA *head=NULL,*p1=NULL,*p2=NULL;
int i;
for(i=1;i<=n;i++)
{ p1=(struct DATA *)malloc(LEN);
scanf("%ld",&p1->num);
p1->next=NULL;
if(i==1) head=p1;
else p2->next=p1;
p2=p1;
}
return(head);
}
struct DATA *merge(struct DATA *head, struct DATA *head2)
{
_______________________
return head;
}
struct DATA *insert(struct DATA *head, struct DATA *d)
{
_______________________
return head;
}
struct DATA *sort(struct DATA *head)
{
_______________________
return head;
}
void print(struct DATA *head)
{
struct DATA *p;
p=head;
while(p!=NULL)
{
printf("%ld",p->num);
p=p->next;
printf("\n");
}
}
main()
{
struct DATA *head, *head2;
int n;
long del_num;
scanf("%d",&n);
head=create(n);
scanf("%d",&n);
head2=create(n);
head = merge(head, head2);
head = sort(head);
print(head);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
输入格式
第一行一个数n,表示第一个列表的数据个数
每二行为n个数
第三行为一个数m
第四行为m个数
输出格式
输出合并后的有序的数据,一行一个数
输入样例
2
4 8
3
9 1 5
输出样例
1
4
5
8
9
代码实现
#include "stdio.h"
#include "malloc.h"
#define LEN sizeof(struct DATA)
struct DATA
{
long num;
struct DATA *next;
};
struct DATA *create(int n)
{
struct DATA *head=NULL,*p1=NULL,*p2=NULL;
int i;
for(i=1;i<=n;i++)
{ p1=(struct DATA *)malloc(LEN);
scanf("%ld",&p1->num);
p1->next=NULL;
if(i==1) head=p1;
else p2->next=p1;
p2=p1;
}
return(head);
}
struct DATA *merge(struct DATA *head, struct DATA *head2) //合并
{
struct DATA *tmp;
tmp=head;
while(tmp->next!=NULL)tmp=tmp->next;
tmp->next=head2;
return head;
}
struct DATA *insert(struct DATA *head, struct DATA *d) //插入
{
struct DATA *old,*element,*tmp;
old = head;
element = d;
if(head==NULL){ //若被插入的链表为空
head=element;
element->next=NULL;
}
else{
while((element->num > old->num) && (old->next != NULL)){ //循环到找到比要插入元素大的位置
tmp=old; //前驱
old=old->next; //向后推进
}
if(element->num <= old->num){ //中间
if(head==old)head=element; //第一个
else tmp->next=element; //遍历到的元素的前驱元素指向插入元素
element->next=old; //要插入元素的下一个等于当前遍历到的元素
}
else{
old->next=element;element->next=NULL; //最后一个
}
}
return head;
}
struct DATA *sort(struct DATA *head) //排序
{
struct DATA *p1,*p2;
p2=head;p1=head;
p2=p2->next;
p1->next=NULL;
p1=p2;
while(p2->next!=NULL)
{
p2=p2->next;
p1->next=NULL;
head=insert(head,p1);
p1=p2;
}
head=insert(head,p1);
return head;
}
void print(struct DATA *head)
{
struct DATA *p;
p=head;
while(p!=NULL)
{
printf("%ld",p->num);
p=p->next;
printf("\n");
}
}
main()
{
struct DATA *head, *head2;
int n;
long del_num;
scanf("%d",&n);
head=create(n);
scanf("%d",&n);
head2=create(n);
head = merge(head, head2);
head = sort(head);
print(head);
}