-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedLists.c
97 lines (78 loc) · 1.43 KB
/
LinkedLists.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
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <stdio.h>
// defining our node
struct Node {
int value;
struct Node* next;
};
struct Node* head; // a global variable
// Finding an element in a list using linked lists
struct Node* get(int pos) {
struct Node *current = head;
int i;
for (i=0; i<pos; i++) {
current = current->next;
}
return current;
}
// INSERTION
void insert(int pos, int value) {
struct Node *newNode = malloc(sizeof(struct Node));
newNode->value = value;
newNode->next = 0;
if (pos == 0) {
newNode->next = head;
head = newNode;
}
else {
struct Node *prev = get(pos-1);
struct Node *curr = prev->next;
newNode->next = curr;
prev->next = newNode;
}
}
// DELETION
void delete(int pos) {
if (pos == 0) {
struct Node *toDelete = head;
head = toDelete->next;
free(toDelete);
}
else {
struct Node *prev = get(pos-1);
struct Node *toDelete = prev->next;
prev->next = toDelete->next;
free(toDelete);
}
}
//
void destroy() {
struct Node *current = head;
struct Node *prev;
while (current != 0) {
prev = current;
current = current->next;
free(prev);
}
}
void display() {
struct Node *current = head;
while (current != 0) {
printf("Address: %p, Value: %d\n", current, current->value);
current = current->next;
}
}
int main() {
head = 0;
insert(0, 1);
insert(1, 2);
insert(2, 3);
insert(3, 4);
insert(0, 5);
insert(0, 6);
display();
printf("\n");
delete(0);
delete(2);
display();
destroy();
}