-
Notifications
You must be signed in to change notification settings - Fork 138
/
ReverseLinkedList.c
83 lines (65 loc) · 914 Bytes
/
ReverseLinkedList.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
#include <stdlib.h>
#include <stdio.h>
struct element
{
int data;
struct element* next;
};
typedef struct element el;
typedef el* LinkedList;
void push(LinkedList* l, int data)
{
LinkedList n = malloc(sizeof(el));
n->data = data;
n->next = NULL;
while (*l)
{
l = &(*l)->next;
}
*l = n;
}
void removeFirst(LinkedList* l)
{
LinkedList n;
if (*l)
{
n = *l;
*l = (*l)->next;
free(n);
}
}
void print(LinkedList l)
{
LinkedList tmp = l;
while (tmp)
{
printf("%d->", tmp->data);
tmp = tmp->next;
}
printf("[]\n");
}
void reverse(LinkedList* l)
{
LinkedList prev, current, next;
current = next = *l;
prev = NULL;
while (current)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*l = prev;
}
int main()
{
LinkedList l = NULL;
push(&l, 1);
push(&l, 2);
push(&l, 3);
print(l);
reverse(&l);
print(l);
return EXIT_SUCCESS;
}