Skip to content

Instantly share code, notes, and snippets.

@liweinan
Created July 1, 2012 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liweinan/3029002 to your computer and use it in GitHub Desktop.
Save liweinan/3029002 to your computer and use it in GitHub Desktop.
Linked List in C
/*
* Mon Jul 02 2012 - Weinan Li <l.weinan@gmail.com> - 0.1
* - Initial version
*/
/*
* include printf()
* and definitions of NULL
*/
#include <stdio.h>
/*
* for malloc() and free()
*/
#include <stdlib.h>
struct node {
int val;
struct node *next, *prev;
};
struct list {
struct node *head;
struct node *curr;
int size;
};
struct list* init_list(int head_val);
struct node* init_node(int val);
struct node* insert_node(struct list *the_list, int val);
void delete_node(struct list *the_list, struct node *node_to_delete);
struct list* init_list(int head_val) {
struct list *new_list;
new_list = malloc(sizeof(struct list));
if (new_list == NULL) {
return NULL;
}
struct node *head_node;
head_node = init_node(head_val);
if (head_node == NULL) {
free(new_list);
return NULL;
}
new_list->head = head_node;
new_list->curr = head_node;
new_list->size = 1;
return new_list;
}
struct node* init_node(int val) {
struct node *the_node;
the_node = malloc(sizeof(struct node));
if (the_node == NULL) {
return NULL;
}
the_node->val = val;
the_node->next = NULL;
the_node->prev = NULL;
return the_node;
}
struct node* insert_node(struct list *the_list, int val) {
struct node *new_node;
new_node = init_node(val);
if (new_node == NULL) {
return NULL;
}
the_list->curr->next = new_node;
new_node->prev = the_list->curr;
the_list->curr = new_node;
the_list->size++;
return new_node;
}
void delete_node(struct list *the_list, struct node *node_to_delete) {
if (the_list == NULL || node_to_delete == NULL)
return;
struct node* p = the_list->head;
while(p!=NULL) {
if (p == node_to_delete) {
if (p == the_list->head) {
the_list->head = the_list->head->next;
} else {
p->prev->next = p->next;
}
the_list->size--;
free(p);
return;
}
p = p->next;
}
}
int main() {
struct list *my_list = init_list(1);
printf("Head of my list: %d\n", my_list->head->val);
printf("Size of my list: %d\n", my_list->size);
insert_node(my_list, 2);
printf("Current node value: %d\n", my_list->curr->val);
printf("Size of my list: %d\n", my_list->size);
insert_node(my_list, 3);
struct node *p = insert_node(my_list, 4);
insert_node(my_list, 5);
struct node *iter = my_list->head;
while(iter != NULL) {
printf("%d\t", iter->val);
iter = iter->next;
}
delete_node(my_list, p);
iter = my_list->head;
printf("\nAfter delete:\n");
while(iter != NULL) {
printf("%d\t", iter->val);
iter = iter->next;
}
printf("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment