Skip to content

Instantly share code, notes, and snippets.

@Zirak
Created October 26, 2013 16:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zirak/7171525 to your computer and use it in GitHub Desktop.
Save Zirak/7171525 to your computer and use it in GitHub Desktop.
//a trivial doubly-linked list implementation
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
struct Node* next;
struct Node* previous;
int value;
} Node;
typedef struct List {
Node* head;
Node* tail;
int length;
} List;
List* create_list () {
List* ret = malloc(sizeof(List));
//yeah, I should check that there was enough memory, blah blah
//but seriously, fuck that
ret->head = NULL;
ret->tail = NULL;
ret->length = 0;
return ret;
}
void destroy_list (List* lst) {
Node* node = lst->head;
while (node) {
Node* next = node->next;
free(node);
node = next;
}
free(lst);
}
void print_node_chain (Node* node) {
printf("%d", node->value);
if (node->next) {
printf(" <-> ");
print_node_chain(node->next);
}
}
void print_list (List* lst) {
Node* node = lst->head;
if (!node) {
return;
}
print_node_chain(node);
printf("\n");
}
void print_list_range (List* lst) {
if (!lst->head || !lst->tail) {
printf("Can't print the range without nodes");
return;
}
printf("[%d, %d]\n", lst->head->value, lst->tail->value);
}
Node* add_value (List* lst, int val) {
Node* node = malloc(sizeof(Node));
node->value = val;
node->next = lst->head;
if (lst->head) {
lst->head->previous = node;
}
if (lst->tail == NULL) {
lst->tail = node;
}
lst->head = node;
lst->length += 1;
return node;
}
void remove_value (List* parent, Node* node) {
//unlink the node from its siblings
//imagine the beginning state is
// 3 <-> node <-> 5
if (node->previous) {
//we unlink 3 from node, and link it to 5
// 3 ---------> 5
// ^---node <---^
//note that 5 is not yet connected to 3. that's fixed in the next if
node->previous->next = node->next;
}
if (node->next) {
//we unlink 5 from node, and link it to 3
// 3 <------> 5
// ^---node---^
//which, after freeing the node, simply looks like
// 3 <-> 5
node->next->previous = node->previous;
}
if (parent->head == node) {
parent->head = node->next;
}
if (parent->tail == node) {
parent->tail = node->previous;
}
parent->length -= 1;
free(node);
}
void print_list_stuff (List* lst) {
printf("%d\n", lst->length);
print_list(lst);
print_list_range(lst);
}
void main () {
List* lst = create_list();
Node* p0 = add_value(lst, 14);
Node* p1 = add_value(lst, 42);
Node* p2 = add_value(lst, -4);
print_list_stuff(lst);
remove_value(lst, p2);
print_list_stuff(lst);
destroy_list(lst);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment