Last active
December 17, 2015 22:29
-
-
Save charlierm/5682703 to your computer and use it in GitHub Desktop.
A painfully simple linked list written in C, with example usage.
This file contains 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
#include <stdlib.h> | |
#include <stdio.h> | |
/** | |
Structure for storing an individual node in the list. | |
**/ | |
typedef struct Node | |
{ | |
int data; | |
struct Node* next; | |
} Node; | |
/** | |
Structure for storing the LinkedList head and length. | |
**/ | |
typedef struct LinkedList | |
{ | |
Node* head; | |
int length; | |
void (*add) (struct LinkedList* list, struct Node* node); | |
} LinkedList; | |
/** | |
Adds a Node to the linked list. | |
@param LinkedList* The LinkedList to add to. | |
@param Node* A pointer to the Node to add. | |
**/ | |
void LinkedList_add(LinkedList* list, Node* node){ | |
node->next = list->head; | |
list->head = node; | |
return; | |
} | |
/** | |
Returns a new instance of a node. | |
**/ | |
Node* Node_new(){ | |
Node* node = malloc(sizeof(Node)); | |
node->next = 0; | |
return node; | |
} | |
/** | |
Returns a new instance of a LinkedList. | |
**/ | |
LinkedList* LinkedList_new(){ | |
LinkedList* list = malloc(sizeof(LinkedList)); | |
list->head = 0; | |
list->add = &LinkedList_add; | |
return list; | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
//Create a LinkedList | |
LinkedList* list = LinkedList_new(); | |
//Add Items to the LinkedList | |
for (int i = 0; i < 500; ++i) | |
{ | |
Node* node = Node_new(); | |
node->data = rand(); | |
list->add(list, node); | |
} | |
//Iterate Items | |
Node* head = list->head; | |
while(head){ | |
printf("%d\n", head->data); | |
head = head->next; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment