-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.h
113 lines (87 loc) · 1.94 KB
/
list.h
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
#ifndef LIST_H
#define LIST_H
// This is a little fancier than what we've been doing, so we'll
// use a "smarter" linked list that keeps track of the root node
typedef struct node
{
int data;
struct node *next;
} Node;
typedef struct list
{
int size;
Node *head;
} List;
List * createList(int value)
{
Node *root = NULL;
root = malloc(sizeof(Node));
root -> data = value;
root -> next = NULL;
List *list = NULL;
list = malloc(sizeof(List));
list -> size = 0;
list -> head = root;
return list;
}
Node * appendToList(int value, List *list)
{
Node *currentNode = list -> head;
// Traverse to the end of the list
while (currentNode -> next != NULL)
{
currentNode = currentNode -> next;
}
Node *newNode = (Node *) malloc(sizeof(Node));
newNode -> data = value;
newNode -> next = NULL;
currentNode -> next = newNode;
list -> size++;
return newNode;
}
Node * prependToList(int value, List *list)
{
// Given the current root, create and set a new one
Node *newRoot = NULL;
newRoot = malloc(sizeof(Node));
newRoot -> data = value;
newRoot -> next = list -> head;
list -> head = newRoot;
list -> size++;
return newRoot;
}
void deleteNode(int value, List *list)
{
Node *previousNode = list -> head;
Node *currentNode = previousNode -> next;
while(previousNode -> data != value && currentNode -> data != value)
{
previousNode = previousNode -> next;
currentNode = currentNode -> next;
}
// If the node to be deleted is the head node
if (previousNode -> data == value)
{
list -> head = list -> head -> next;
}
else
{
previousNode -> next = previousNode -> next -> next;
}
list -> size--;
previousNode = NULL;
currentNode = NULL;
free(previousNode);
free(currentNode);
}
void displayList(List *list)
{
Node *node = list -> head;
while (node != NULL)
{
printf("%d ", node -> data);
node = node -> next;
}
printf("\n");
}
#endif