-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedlist.c
More file actions
72 lines (64 loc) · 1.6 KB
/
linkedlist.c
File metadata and controls
72 lines (64 loc) · 1.6 KB
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
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "linkedlist.h"
linkedlist_t* CreateLinkedListOfFiveItems(){
linkedlist_t* list = CreateLinkedList();
int i;
for (i = 0; i < 5; i++) {
AppendToLinkedList(list, NULL);
}
return list;
}
linkedlist_t* CreateLinkedList(){
// allocating memory for a new linked list
linkedlist_t* list = (linkedlist_t*)malloc(sizeof(list));
// assigning null as a head value of the new list
list->head = NULL;
return list;
}
void PrintLinkedList(linkedlist_t* list){
node_t* iter = list->head;
while (iter != NULL) {
printf("%s", iter->data);
iter = iter->next;
}
}
void FreeLinkedList(linkedlist_t* list){
node_t* current = list->head;
node_t* next;
// we are freeing nodes until the next value is null
while(current != NULL) {
next = current->next;
free(current->data);
free(current);
current = next;
}
// freeing up the list itself
free(list);
}
node_t* TraverseLinkedList(node_t* head) {
node_t* iterator = head;
while (iterator->next != NULL) {
iterator = iterator->next;
}
return iterator;
}
void AppendToLinkedList(linkedlist_t* list, char* data){
// create a new node with the given data
node_t* newNode = (node_t*)malloc(sizeof(node_t));
// allocate memory for the node data
char* buf = (char*)malloc(strlen(data)*sizeof(char*));
// copy data over to buf
strcpy(buf, data);
// set buf as data for the node
newNode->data = buf;
newNode->next = NULL;
// check if the head of the list is null
if (list->head == NULL) {
list->head = newNode;
} else {
node_t* tail = TraverseLinkedList(list->head);
tail->next = newNode;
}
}