Last active
September 23, 2019 06:47
-
-
Save ian910297/d03edc271105854a0cc3fcf68c1cb527 to your computer and use it in GitHub Desktop.
Indirect remove linked list
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 list { | |
struct list_entry *head; | |
} list; | |
typedef struct list_entry { | |
int val; | |
struct list_entry *next; | |
} list_entry; | |
void remove_ptr(list *list, list_entry *target) | |
{ | |
// The "indirect" pointer points to the *address* | |
// of the thing we'll update. | |
list_entry **indirect = &list->head; | |
// Walk the list, looking for the thing that | |
// points to the node we want to remove. | |
while (*indirect != target) | |
indirect = &(*indirect)->next; | |
*indirect = target->next; | |
} | |
void print(list_entry *head) { | |
list_entry *cur = head; | |
while(cur!=NULL) { | |
printf("%d ", cur->val); | |
cur = cur->next; | |
} | |
printf("\n"); | |
} | |
int main() { | |
list listA; | |
listA.head = malloc(sizeof(list_entry)); | |
list_entry *cur; | |
cur = listA.head; | |
int i; | |
for(i=0; i<3; i++) { | |
cur->val = i; | |
cur->next = malloc(sizeof(list_entry)); | |
cur = cur->next; | |
} | |
cur->val = i; | |
cur->next = NULL; | |
print(listA.head); | |
remove_ptr(&listA, listA.head); | |
print(listA.head); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment