Last active
April 12, 2016 12:00
-
-
Save anthonynsimon/2d7dbace094ba9e521f0ee235da18876 to your computer and use it in GitHub Desktop.
Quick and dirty linked list in C
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
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct node { | |
int value; | |
struct node* next; | |
} node_t; | |
typedef struct list { | |
node_t* head; | |
} list_t; | |
list_t* create_list() { | |
list_t* list = malloc(sizeof(list_t)); | |
list->head = NULL; | |
return list; | |
} | |
void traverse_list(list_t* list) { | |
node_t* current = list->head; | |
while (current != NULL) { | |
printf("%d\n", current->value); | |
current = current->next; | |
} | |
} | |
node_t* create_node(int value) { | |
node_t* node = malloc(sizeof(node_t)); | |
node->value = value; | |
node->next = NULL; | |
return node; | |
} | |
void push_to_list(list_t* list, int value) { | |
node_t* current = list->head; | |
if (list->head == NULL) { | |
list->head = create_node(value); | |
} | |
else { | |
while (current->next != NULL) { | |
current = current->next; | |
} | |
current->next = create_node(value); | |
} | |
} | |
void remove_from_list(list_t* list, int index) { | |
node_t* current_node = list->head; | |
node_t* previous_node = NULL; | |
int current_index = 0; | |
while (current_node != NULL) { | |
if (current_index == index) { | |
if (previous_node == NULL) { | |
list->head = current_node->next; | |
} | |
else { | |
previous_node->next = current_node->next; | |
free (current_node); | |
} | |
return; | |
} | |
current_index++; | |
previous_node = current_node; | |
current_node = current_node->next; | |
} | |
} | |
void insert_to_list(list_t* list, int index, int value) { | |
node_t* current_node = list->head; | |
node_t* previous_node = NULL; | |
int current_index = 0; | |
while (current_node != NULL) { | |
if (current_index == index) { | |
if (previous_node == NULL) { | |
list->head = create_node(value); | |
list->head->next = current_node; | |
} | |
else { | |
previous_node->next = create_node(value); | |
previous_node->next->next = current_node; | |
} | |
return; | |
} | |
current_index++; | |
previous_node = current_node; | |
current_node = current_node->next; | |
} | |
} | |
int main(void) { | |
list_t* list = create_list(); | |
push_to_list(list, 100); | |
push_to_list(list, 200); | |
push_to_list(list, 300); | |
push_to_list(list, 400); | |
remove_from_list(list, 3); | |
insert_to_list(list, 0, 50); | |
insert_to_list(list, 0, 25); | |
insert_to_list(list, 4, 350); | |
traverse_list(list); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment