-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_list.c
More file actions
72 lines (53 loc) · 1.07 KB
/
reverse_list.c
File metadata and controls
72 lines (53 loc) · 1.07 KB
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
/*
* 常见题目:
* 反转一个单链表
*
* */
#include <stdio.h>
#include <stdlib.h>
struct List {
int value;
struct List* next;
};
struct List *reverse_list(struct List *p)
{
if (!p)
return NULL;
struct List *before = NULL;
struct List *current = p;
struct List *after = p->next;
while(1) {
if (!current->next)
break;
current->next = before;
before = current;
current = after;
after = current->next;
}
current->next = before;
return current;
}
void print_list(struct List *p)
{
printf("\n");
while (p) {
printf("%d, ", p->value);
p = p->next;
}
printf("\n");
}
int main()
{
struct List *in = malloc(sizeof(struct List));
struct List *out;
in->value = 9;
in->next = malloc(sizeof(struct List));
in->next->value = 8;
in->next->next = malloc(sizeof(struct List));
in->next->next->value = 7;
in->next->next->next = NULL;
print_list(in);
out = reverse_list(in);
print_list(out);
return 0L;
}