Skip to content

Instantly share code, notes, and snippets.

Created January 22, 2013 22:35
Show Gist options
  • Save anonymous/4599323 to your computer and use it in GitHub Desktop.
Save anonymous/4599323 to your computer and use it in GitHub Desktop.
In response to: http://meta.slashdot.org/story/12/10/11/0030249/linus-torvalds-answers-your-questions An explanation of the two different types of singly-linked list removal explained by Linus Torvalds, using the variable names introduced here: http://stackoverflow.com/questions/12914917/
#include <stdio.h>
typedef struct ll {
int value;
struct ll *next;
} ll;
void print_list(ll *list_head)
{
ll *entry = list_head;
while (entry) {
printf("%d\n", entry->value);
entry = entry->next;
}
}
#define REMOVE 1
int main()
{
/* Create a list [1,2,3,4] */
ll *list_head = &((ll){1, &((ll){2, &((ll){3, &((ll){4, NULL }) }) }) });
/* Creating auto (not malloc'd) allows for auto-cleanup after removal */
print_list(list_head);
/* PREV VERSION *//*
ll *prev = NULL;
ll *entry = list_head;
while (entry) {
if (entry->value == REMOVE) {
if (prev)
prev->next = entry->next;
else
list_head = entry->next;
}
prev = entry;
entry = entry->next;
}*/
/* LINUS VERSION */
ll **pp = &list_head;
while (*pp != NULL) {
if ((*pp)->value == REMOVE) {
(*pp) = (*pp)->next;
} else {
pp = &((*pp)->next);
}
}
/* Print the list with the specified value removed */
print_list(list_head);
return 0;
}
@goakley
Copy link

goakley commented Jan 22, 2013

Whoopse, forgot to log in when I posted this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment