Skip to content

Instantly share code, notes, and snippets.

@CptKirklnd
Created August 26, 2015 18:37
Show Gist options
  • Save CptKirklnd/1288895d5efcf76e79cb to your computer and use it in GitHub Desktop.
Save CptKirklnd/1288895d5efcf76e79cb to your computer and use it in GitHub Desktop.
That OTHER time I had to write a linked list in C.
#include <stdio.h>
#include <stdlib.h>
//very simple linked list struct
struct ll {
int x;
//Add pointer info
struct ll *next;
struct ll *prev;
};
//add a node to the list
void add_node(struct ll **list, int y){
//pointers
struct ll *nn_ptr;
struct ll *prevn_ptr;
struct ll *curn_ptr;
//creat space for the new node using malloc
struct ll *newNode = (struct ll*) malloc(sizeof(struct ll));
//if malloc worked, add data
if (newNode != NULL) {
newNode->x = y;
}
//find the correct location
curn_ptr = *list;
prevn_ptr = NULL;
if (curn_ptr == NULL){
*list = newNode;
newNode->next = NULL;
newNode->prev = NULL;
}
else{
while(curn_ptr->next != NULL){
curn_ptr = curn_ptr->next;
}
//insrt the new node
newNode->next = NULL;
//firt if at start of the list
//using our curn_ptr
newNode->prev = curn_ptr;
curn_ptr->next = newNode;
}
}
//remove a node containing y
void remove_node(struct ll **list, int y){
//pointers
struct ll *prev_n;
struct ll *cur_n;
struct ll *temp;
//check if its the first node
if((*list)->x == y) {
//remove the first node
cur_n = *list;
cur_n->next = NULL;
cur_n->prev = NULL;
temp = cur_n;
*list = NULL;
cur_n = NULL;
//make sure to free the old node
free(temp);
}
else{
//find the correct node
prev_n = (*list);
cur_n = (*list)->next;
while(cur_n->x != y){
prev_n = cur_n;
cur_n = cur_n->next;
}
if (cur_n->next != NULL) {
cur_n->next->prev = prev_n;
}
prev_n->next = cur_n->next;
temp = cur_n;
cur_n = *list; //reset cur back to the start of the list for neatness
}
free(temp);
}
//print the list
void print_list(struct ll* list){
struct ll *current;
current = list;
while (current != NULL){
printf("%d\n",current->x);
current = current->next;
}
}
int main(int argc, const char * argv[]) {
struct ll* test=0;
add_node(&test, 10);
add_node(&test, 8);
add_node(&test, 8);
add_node(&test, 11);
add_node(&test, 9);
print_list(test);
remove_node(&test, 11);
print_list(test);
remove_node(&test, 9);
print_list(test);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment