Reverse a singly linked list
Source
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
|
#include <stdio.h> typedef struct Node {
char data;
struct Node* next;
} Node; void print_list(Node* root) {
while (root) {
printf ( "%c " , root->data);
root = root->next;
}
printf ( "\n" );
} Node* reverse(Node* root) { Node* new_root = 0;
while (root) {
Node* next = root->next;
root->next = new_root;
new_root = root;
root = next;
}
return new_root;
} int main() {
Node d = { 'd' , 0 };
Node c = { 'c' , &d };
Node b = { 'b' , &c };
Node a = { 'a' , &b };
Node* root = &a;
print_list(root);
root = reverse(root);
print_list(root);
return 0;
} |