蔡子经数据结构1.15

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


#include <stdlib.h>

typedef struct
{
int val;
struct * next;
} node;

node* createNode()
{
node *ret = (node*)malloc(sizeof(node));
ret->val = 0;
ret->next = NULL;
return ret;
}

node* createLink(int n)
{
node *head = createNode();
for(int i = 0; i < n; ++i)
{
node *p = createNode();
p->val = rand()%100;
p->next = head->next;
head->next = p;
}
return head;
}

node* merge(node *x, node *y)
{
node *head = createNode();
node *px = x->next;
free(x);
node *py = y->next;
free(y);
node *ph = head;
while(px && py)
{
node *tx = px;
px = px->next;
node *ty = py;
py = py->next;
tx->next = ty;
ty->next = NULL;
ph->next = tx;
ph = ty;
}
if(px) ph->next = px;
if(py) ph->next = py;
return head;
}

void print(node *p)
{
p = p->next;
while(p)
{
printf("%d ",p->val);
p = p->next;
}
puts("");
return ;
}

int main()
{
srand(time(NULL));
node *x = createLink(5);
print(x);
node *y = createLink(6);
print(y);
node *head = merge(x, y);
print(head);
return 0;
}