Created
December 25, 2013 00:59
-
-
Save Preetam/8119254 to your computer and use it in GitHub Desktop.
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> | |
struct list_node { | |
int val; | |
struct list_node* next; | |
}; | |
typedef struct list_node node_t; | |
typedef struct { | |
node_t* root; | |
} list_t; | |
node_t* | |
list_insert_impl(node_t* root, int val); | |
node_t* | |
list_remove_impl(node_t* root, int val); | |
list_t* | |
new_list() { | |
list_t* l = (list_t*)malloc(sizeof(list_t)); | |
return l; | |
} | |
void | |
list_insert(list_t* list, int val) { | |
list->root = list_insert_impl(list->root, val); | |
} | |
void | |
list_remove(list_t* list, int val) { | |
list->root = list_remove_impl(list->root, val); | |
} | |
void | |
list_destroy(list_t* list) { | |
while(list->root) { | |
list_remove(list, list->root->val); | |
} | |
free(list); | |
} | |
node_t* | |
list_create_node(int val) { | |
node_t* n = (node_t*)malloc(sizeof(node_t)); | |
n->val = val; | |
return n; | |
} | |
node_t* | |
list_insert_impl(node_t* root, int val) { | |
if(root == NULL) { | |
return list_create_node(val); | |
} | |
if(val < root->val) { | |
node_t* n = list_create_node(val); | |
n->next = root; | |
return n; | |
} | |
root->next = list_insert_impl(root->next, val); | |
return root; | |
} | |
node_t* | |
list_remove_impl(node_t* root, int val) { | |
if(root == NULL) { | |
return NULL; | |
} | |
if(root->val == val) { | |
node_t* next = root->next; | |
free(root); | |
return next; | |
} | |
root->next = list_remove_impl(root->next, val); | |
return root; | |
} | |
void | |
main() { | |
node_t* curr; | |
int i; | |
list_t* l = new_list(); | |
list_insert(l, 0); | |
list_insert(l, 5); | |
list_insert(l, 3); | |
list_insert(l, 9); | |
list_insert(l, -5); | |
curr = l->root; | |
while(curr) { | |
printf("%d\n", curr->val); | |
curr = curr->next ; | |
} | |
list_remove(l, 3); | |
list_remove(l, 2); | |
curr = l->root; | |
printf("-----\n"); | |
while(curr) { | |
printf("%d\n", curr->val); | |
curr = curr->next ; | |
} | |
list_destroy(l); | |
} | |
/* Valgrind output: | |
==28499== | |
==28499== HEAP SUMMARY: | |
==28499== in use at exit: 0 bytes in 0 blocks | |
==28499== total heap usage: 6 allocs, 6 frees, 88 bytes allocated | |
==28499== | |
==28499== All heap blocks were freed -- no leaks are possible | |
==28499== | |
==28499== For counts of detected and suppressed errors, rerun with: -v | |
==28499== Use --track-origins=yes to see where uninitialised values come from | |
==28499== ERROR SUMMARY: 5 errors from 5 contexts (suppressed: 2 from 2) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment