forked from zhuxinquan/Data-Structure-And-Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_list.c
116 lines (109 loc) · 2.12 KB
/
merge_list.c
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*************************************************************************
> File Name: prelink.c
> Author: zhuxinquan
> Mail: [email protected]
> Created Time: 2015年09月09日 星期三 21时11分51秒
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
void print_link(node * );
node * creat_link()
{
node * h = (node *)malloc(sizeof(node));
h->next = NULL;
node * s, *r = h;
int x;
scanf("%d", &x);
while(x != -1)
{
s = (node *)malloc(sizeof(node));
s->data = x;
s->next = r->next;
r->next = s;
r = s;
scanf("%d", &x);
}
return h;
}
node * prelink(node * h1, node *h2)
{
node * h, *t, *s, *p;
h = (node *)malloc(sizeof(node));
h->next = NULL;
while(h1->next && h2->next)
{
if(h1->next->data < h2->next->data)
{
p = h1->next;
h1->next = p->next;
}
else
{
p = h2->next;
h2->next = p->next;
}
p->next = NULL;
if(!h->next)
{
h->next = t = p;
}
else
{
if(t->data == p->data)
{
free(p);
}
else
{
t->next = p;
t = p;
}
}
}
if(h1->next){
s = h1->next;
}
else{
s = h2->next;
}
while(s)
{
p = s;
s = s->next;
p->next = NULL;
if(t->data == p->data){
free(p);
}else{
t->next = p;
}
}
return h;
}
void print_link(node * h)
{
node * p;
p = h->next;
while(p != NULL)
{
printf("%4d", p->data);
p = p->next;
}
}
int main(void)
{
node * h1, *h2;
printf("input link1(-1 end):\n");
h1 = creat_link();
printf("input link2(-1 end):\n");
h2 = creat_link();
h1 = prelink(h1, h2);
printf("合并后为:\n");
print_link(h1);
printf("\n");
return 0;
}