Skip to content

Instantly share code, notes, and snippets.

@ian910297
Last active September 23, 2019 06:47
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 ian910297/d03edc271105854a0cc3fcf68c1cb527 to your computer and use it in GitHub Desktop.
Save ian910297/d03edc271105854a0cc3fcf68c1cb527 to your computer and use it in GitHub Desktop.
Indirect remove linked list
#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