fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct node {
  5. int value;
  6. struct node *next;
  7. };
  8.  
  9. void display_list(struct node *list) {
  10. struct node *cur;
  11. printf("list: %p, values:", list);
  12. for(cur = list; cur != NULL; cur = cur->next) {
  13. printf(" %d", cur->value);
  14. }
  15. printf("\n");
  16. }
  17.  
  18. void add_to_front_of_list(struct node **list, int n) {
  19. struct node *node = malloc(sizeof(node));
  20. node->value = n;
  21. node->next = *list;
  22. *list = node;
  23. }
  24.  
  25. void free_node(struct node **n)
  26. {
  27. struct node *next = (*n)->next;
  28. free(*n);
  29. *n = next;
  30. }
  31.  
  32. void delete_from_list(struct node **list, int n) {
  33. while (*list != NULL) {
  34. if ((*list)->value == n) {
  35. free_node(list);
  36. break;
  37. }
  38. list = &((*list)->next);
  39. }
  40. }
  41.  
  42. int main(void) {
  43. struct node *list = NULL;
  44.  
  45. for(int i = 5; i > 0; --i) {
  46. add_to_front_of_list(&list, i);
  47. }
  48.  
  49. display_list(list);
  50.  
  51. delete_from_list(&list, 1);
  52. display_list(list);
  53.  
  54. delete_from_list(&list, 3);
  55. display_list(list);
  56.  
  57. delete_from_list(&list, 5);
  58. display_list(list);
  59.  
  60. return 0;
  61. }
Success #stdin #stdout 0.01s 5464KB
stdin
Standard input is empty
stdout
list: 0x55f81d6242e0, values: 1 2 3 4 5
list: 0x55f81d6242c0, values: 2 3 4 5
list: 0x55f81d6242c0, values: 2 4 5
list: 0x55f81d6242c0, values: 2 4