Created
December 24, 2017 07:05
-
-
Save cuixin/136c4934793a2723c1abe2593be222ec to your computer and use it in GitHub Desktop.
This is an example of using pointer of pointer to delete singly linked list element.
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 <stdio.h> | |
#include <stdlib.h> | |
typedef struct node { | |
int val; | |
struct node* next; | |
} node_t; | |
void print_list(node_t* head) { | |
node_t* cur = head; | |
while (cur != NULL) { | |
if (cur->next != NULL) { | |
printf("%d->", cur->val); | |
} else { | |
printf("%d", cur->val); | |
} | |
cur = cur->next; | |
} | |
printf("\n"); | |
} | |
node_t* init_node(int v) { | |
node_t* node = malloc(sizeof(node_t)); | |
node->val = v; | |
return node; | |
} | |
node_t* append_node(node_t* head, int v) { | |
node_t* next = init_node(v); | |
head->next = next; | |
return next; | |
} | |
void delete_node(node_t** cur) { | |
node_t* next = (*cur)->next; | |
if (next) { | |
free(*cur); | |
*(*cur) = *next; | |
*cur = NULL; | |
return; | |
} | |
free(*cur); | |
*cur = NULL; | |
} | |
void free_list(node_t** head) { | |
node_t* cur = *head; | |
while (cur != NULL) { | |
free(cur); | |
cur = cur->next; | |
} | |
*head = NULL; | |
} | |
int main() { | |
node_t* head = init_node(0); | |
node_t* last = head; | |
node_t* will_be_del_node = NULL; | |
for (int i=1; i < 10; i++) { | |
node_t* cur = append_node(last, i); | |
if (i == 5) { | |
will_be_del_node = cur; | |
printf("Delete %d\n", cur->val); | |
} | |
last = cur; | |
} | |
print_list(head); | |
delete_node(&will_be_del_node); | |
print_list(head); | |
free_list(&head); | |
print_list(head); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment