Created
September 25, 2017 06:31
-
-
Save nhatbui/284b3c1d4b23c2f70cf88ebb1a54cb8c to your computer and use it in GitHub Desktop.
Linked List implementation in C. Iteration in only one direction. Optimized for appending. (nothing special, just for copy pasta)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// One element of the list | |
// You should replace the "data" field | |
// with a type of your choice. | |
struct Node | |
{ | |
struct Node * next; | |
/* Replace this with the data of your choice */ | |
char * data; | |
}; | |
// Finally, our "List" struct | |
struct List | |
{ | |
int size; | |
struct Node * start; | |
struct Node * end; | |
}; | |
// Appends a node to the end of the list | |
void appendNode(struct List * list, struct Node * node) | |
{ | |
// Check if a list already exists | |
if (!list->start) | |
{ | |
list->start = node; | |
list->end = node; | |
list->size += 1; | |
} | |
else | |
{ | |
(list->end)->next = node; | |
list->end = node; | |
list->size += 1; | |
} | |
} | |
// Deletes list. You should handle deleting | |
// of your "data" field in here as well. | |
void deleteList(struct LinkedList * list) | |
{ | |
struct Node * nodeItr = list->start; | |
if(!nodeItr) | |
{ | |
// We trust that it's empty | |
// But these are checks that should pass | |
/* | |
if(list->size > 0) | |
{ | |
fprintf( | |
stderr, | |
"Size if not 0? Size: %i. Uh oh.\n", | |
list->size | |
); | |
} | |
if(list->end) | |
{ | |
fprintf( | |
stderr, | |
"This list has a non-null end. Uh shit.\n" | |
); | |
} | |
*/ | |
return; | |
} | |
while(nodeItr) | |
{ | |
struct Node * temp = nodeItr; | |
nodeItr = nodeItr->next; | |
/* if your data requires it, delete it here */ | |
if(temp->data) | |
{ | |
free(temp->data); | |
} | |
free(temp); | |
} | |
list->start = NULL; | |
list->end = NULL; | |
list->size = 0; | |
} | |
// Example of iterating through the list and doing something | |
// with it. | |
void argsListToArray(struct List * list, char * dataArray[]) | |
{ | |
struct Node * nodeItr = list->start; | |
int i = 0; | |
while(nodeItr) | |
{ | |
struct Node * temp = nodeItr; | |
nodeItr = nodeItr->next; | |
dataArray[i] = temp->data; | |
i++; | |
} | |
dataArray[i] = NULL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment