-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedList.c
131 lines (118 loc) · 3.24 KB
/
linkedList.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "linkedList.h"
linkListElement_t* head = 0;
int linkedList_add(dataStructure_t* x)
{
if (!x) return __LINE__;
linkListElement_t* newItem = malloc(sizeof(linkListElement_t));
if (!newItem) return __LINE__;
newItem->data = *x;
if (!head)
{
//handle case where this is the first element in the list
head = newItem;
newItem->next = 0;
}
else
{
//sort alphabetically by last name...
linkListElement_t* currentItem = head;
// 1-off - check to see if the new item is ahead of the head...
if (strcmp(newItem->data.lastName, currentItem->data.lastName) <= 0)
{
//new item is lower
head = newItem;
newItem->next = currentItem;
}
else
{
//traverse the list...
do
{
linkListElement_t* nextItem = currentItem->next;
if (!nextItem)
{
// at the end of the list... just add here.
currentItem->next = newItem;
newItem->next = 0;
break;
}
else
{
if (strcmp(newItem->data.lastName, nextItem->data.lastName) <= 0)
{
//new item is lower than next item
currentItem->next = newItem;
newItem->next = nextItem;
break;
}
}
} while (1);
}
}
return 0;
}
int linkedList_print(void)
{
linkListElement_t* currentItem = head;
printf("\n\nLIST:\n");
while (currentItem != 0)
{
printf("%s, %s\n",currentItem->data.lastName, currentItem->data.firstName);
currentItem = currentItem->next;
}
return 0;
}
int linkedList_remove(char* lastName)
{
if (!lastName) return __LINE__;
if (!head) return __LINE__;
//sort alphabetically by last name...
linkListElement_t* currentItem = head;
// 1-off - check to see if the first item matches...
if (strcmp(lastName, currentItem->data.lastName) == 0)
{
head = currentItem->next;
free(currentItem);
}
else
{
//traverse the list...
do
{
linkListElement_t* nextItem = currentItem->next;
if (!nextItem)
{
// at the end of the list... no matches found...
return __LINE__;
}
else
{
if (strcmp(lastName, nextItem->data.lastName) == 0)
{
//next item matches
currentItem->next = nextItem->next;
free(nextItem);
break;
}
}
currentItem = nextItem;
} while (1);
}
return 0;
}
int linkedList_destroy(void)
{
linkListElement_t* currentItem = head;
while (currentItem != 0)
{
linkListElement_t* nextItem = currentItem->next;
free(currentItem);
//update currentItem for next loop
currentItem = nextItem;
}
head = 0;
return 0;
}