-
Notifications
You must be signed in to change notification settings - Fork 2
/
linked_list.c
113 lines (104 loc) · 2.41 KB
/
linked_list.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
Group 36
2017B4A70495P Manan Soni
2017B4A70549P Siddharth Singh
2017B4A70636P Nayan Khanna
2017B4A70740P Aditya Tulsyan
*/
#include "linked_list.h"
linked_list *create_linked_list()
{
linked_list *ll = calloc(1, sizeof(linked_list));
ll->num_nodes = 0;
ll->head = NULL;
ll->tail = NULL;
return ll;
}
void ll_free(linked_list *ll){
ll_node *temp = ll->head;
while( temp ){
ll->head = ll->head->next;
free(temp);
temp = ll->head;
}
free(ll);
}
void ll_add_at(linked_list *ll, void *data, int idx)
{
assert(idx <= ll->num_nodes && idx >= 0, "linked list insertion index valid");
ll_node *new_node = calloc(1, sizeof(ll_node));
new_node->data = data;
if (ll->num_nodes == 0)
{
new_node->next = NULL;
new_node->prev = NULL;
ll->head = new_node;
ll->tail = new_node;
ll->num_nodes = 1;
}
else
{
if (idx == 0)
{
new_node->next = ll->head;
ll->head->prev = new_node;
new_node->prev = NULL;
ll->head = new_node;
(ll->num_nodes)++;
}
else if (idx == ll->num_nodes)
{
ll->tail->next = new_node;
new_node->prev = ll->tail;
new_node->next = NULL;
ll->tail = new_node;
(ll->num_nodes)++;
}
else
{
ll_node *temp;
ll_node *pre_temp;
pre_temp = ll->head;
temp = pre_temp->next;
int i = 1;
while (i < idx)
{
temp = temp->next;
pre_temp = pre_temp->next;
i++;
}
pre_temp->next = new_node;
temp->prev = new_node;
new_node->next = temp;
new_node->prev = pre_temp;
(ll->num_nodes)++;
}
}
}
void ll_append(linked_list *ll, void *data)
{
ll_add_at(ll, data, ll->num_nodes);
}
void *ll_get(linked_list *ll, int idx)
{
assert(idx < ll->num_nodes && idx >= 0, "index valid while getting from linked list");
if (idx == 0)
{
return ll->head->data;
}
else if (idx == ll->num_nodes - 1)
{
return ll->tail->data;
}
else
{
int i = 0;
ll_node *temp = ll->head;
while (i < idx)
{
temp = temp->next;
i++;
}
return temp->data;
}
}