/
reserve_link.c
84 lines (71 loc) · 1.1 KB
/
reserve_link.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
#include <stdio.h>
#include <malloc.h>
typedef struct node {
int value;
struct node *next;
}node_t;
node_t *create_link()
{
node_t *head = NULL, *p;
int i;
for (i = 1; i < 10; i++) {
p = (node_t *)malloc(sizeof(node_t));
if (NULL == p)
break;
p->value = i;
if (NULL == head) {
head = p;
head->next = NULL;
}
else {
p->next = head;
head = p;
}
}
return head;
}
void destroy_link(node_t *link)
{
node_t *p, *q;
p = link;
while (p) {
q = p->next;
free(p);
p = q;
}
}
node_t *reverse_link(node_t *link)
{
node_t *prev, *cur, *next;
if (NULL == link || NULL == link->next)
return link;
prev = link;
cur = link->next;
while (cur){
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
link->next = NULL;
return prev;
}
void print_link(node_t *link)
{
while (link) {
if (link->next)
printf("%d->", link->value);
else
printf("%d\n", link->value);
link = link->next;
}
}
int main()
{
node_t *link = create_link();
print_link(link);
node_t *link2 = reverse_link(link);
print_link(link2);
destroy_link(link2);
return 0;
}