Created
November 4, 2012 20:04
-
-
Save wjlafrance/4013407 to your computer and use it in GitHub Desktop.
delete node from linked list
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
#import <stdio.h> | |
#import <stdlib.h> | |
typedef struct node_s { | |
struct node_s *next; | |
void *data; | |
} node_t; | |
typedef node_t list_t; | |
list_t * populateList() { | |
node_t *zeroth = malloc(sizeof(node_t)); | |
node_t *first = malloc(sizeof(node_t)); | |
node_t *second = malloc(sizeof(node_t)); | |
node_t *third = malloc(sizeof(node_t)); | |
node_t *fourth = malloc(sizeof(node_t)); | |
node_t *fifth = malloc(sizeof(node_t)); | |
zeroth->data = "Zeroth node."; | |
zeroth->next = first; | |
first->data = "First node."; | |
first->next = second; | |
second->data = "Second node."; | |
second->next = third; | |
third->data = "Third node."; | |
third->next = fourth; | |
fourth->data = "Fourth node."; | |
fourth->next = fifth; | |
fifth->data = "Fifth node."; | |
fifth->next = NULL; | |
return zeroth; | |
} | |
void printList(list_t *list) { | |
node_t *node = list; | |
do { | |
printf("%s\n", node->data); | |
node = node->next; | |
} while (node != NULL); | |
} | |
void deleteElement(list_t *list, int index) { | |
node_t *node = list; | |
for (int i = 0; i < index - 1; i++) { | |
node = node->next; | |
} | |
node_t *new_next = node->next->next; | |
node_t *old_next = node->next; | |
free(old_next); | |
node->next = new_next; | |
} | |
void deallocList(list_t *list) { | |
node_t *node = list; | |
do { | |
node_t *next = node->next; | |
free(node); | |
node = next; | |
} while (node != NULL); | |
} | |
int main(int argc, char **argv) { | |
list_t *list = populateList(); | |
printList(list); | |
printf("\n\n"); | |
deleteElement(list, 3); | |
printf("Deleted third element."); | |
printf("\n\n"); | |
printList(list); | |
deallocList(list); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment