Skip to content

Instantly share code, notes, and snippets.

@grantg012
Last active April 19, 2022 21:43
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 grantg012/a3b8afeecdc495526ab268d01b0698f2 to your computer and use it in GitHub Desktop.
Save grantg012/a3b8afeecdc495526ab268d01b0698f2 to your computer and use it in GitHub Desktop.
Linked List Magic
/**
* Simple example of linked lists in C. The special part is the use of a pointer to a pointer
* which very elegantly can remove a node anywhere in the list without special case handling.
*/
#include <stdio.h>
#include <stdint.h>
typedef struct ll_node_s
{
struct ll_node_s *mpNext;
uint32_t data;
} ll_node_t;
void removeNode(ll_node_t **ptr, ll_node_t const *target)
{
while(*ptr != target)
{
ptr = &((*ptr)->mpNext);
}
*ptr = (*ptr)->mpNext;
}
void printList(ll_node_t const *ptr)
{
while(ptr != NULL)
{
fprintf(stdout, "%d ", ptr->data);
ptr = ptr->mpNext;
}
fputc('\n', stdout);
}
int main()
{
ll_node_t Node0 = { NULL, 0};
ll_node_t Node1 = { &Node0, 1};
ll_node_t Node2 = { &Node1, 2};
ll_node_t Node3 = { &Node2, 3};
ll_node_t Node4 = { &Node3, 4};
ll_node_t Node5 = { &Node4, 5};
ll_node_t *myList = &Node5;
printList(myList);
removeNode(&myList, &Node3);
printList(myList);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment