Skip to content

Instantly share code, notes, and snippets.

@squiidz
Last active August 23, 2017 21:20
Show Gist options
  • Save squiidz/8ead2c443b528016bf7e3c6dab07b38a to your computer and use it in GitHub Desktop.
Save squiidz/8ead2c443b528016bf7e3c6dab07b38a to your computer and use it in GitHub Desktop.
Clang double pointer linked list
#include "stdio.h"
#include "stdlib.h"
typedef struct _node {
int value;
struct _node *next;
} node;
// Create a new node with the provided value
node *new_node(int _value) {
node *n = (node*)malloc(sizeof(node));
n->value = _value;
n->next = NULL;
return n;
}
node *build_list(int start, int end) {
// Create a node with the 0 value
node *head = new_node(0);
// For n iteration, create a node wich point to the last one.
for(int i = end; i >= start; i--) {
// Create a new node with i value.
node *nn = new_node(i);
// Set it's next member to head which is the last node created.
nn->next = head;
// Set head to the newly created node,
// so the next iteration could use it to set is next member.
head = nn;
}
return head;
}
// Delete the node with the value equal to _value,
// using a double pointer of the head of the list.
node *delete_node(node **head, int _value) {
// Store the double pointer head.
node **_head = head;
// Check if the content of the current node is NULL,
// if not it check if the value match the _value param.
while(*_head && (**_head).value != _value) {
// If not matching, it store the next node of the linked list
// in the head double pointer and continue.
_head = &(*_head)->next;
}
// Check to be sure head is not NULL
if(*_head == NULL)
return NULL;
// Assign the matching value node to the del_node variable.
node *del_node = *_head;
// Reassign the original head to the deleted node
// wihch it was pointing to in the next member.
*_head = del_node->next;
// Set the next member of the deleted node to NULL.
del_node->next = NULL;
return del_node;
}
int main() {
// Create a list of n element and return the head.
node *head = build_list(0, 50);
// Look for the node containing the value, delete it from the list and return it.
node *del_node = delete_node(&head, 13);
printf("Head point to address: %p\n", head);
printf("Head address is: %p\n", &head);
printf("%d\n", del_node->value);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment