fork 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. struct node* 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. return node;
  23. }
  24.  
  25. struct node* free_node(struct node *n)
  26. {
  27. struct node *next = n->next;
  28. free(n);
  29. return next;
  30. }
  31.  
  32. struct node* delete_from_list(struct node *list, int n) {
  33. struct node **ptr = &list;
  34. while (*ptr != NULL) {
  35. if ((*ptr)->value == n) {
  36. *ptr = free_node(*ptr);
  37. break;
  38. }
  39. ptr = &((*ptr)->next);
  40. }
  41. return list;
  42. }
  43.  
  44. int main(void) {
  45. struct node *list = NULL;
  46.  
  47. for(int i = 5; i > 0; --i) {
  48. list = add_to_front_of_list(list, i);
  49. }
  50.  
  51. display_list(list);
  52.  
  53. list = delete_from_list(list, 1);
  54. display_list(list);
  55.  
  56. list = delete_from_list(list, 3);
  57. display_list(list);
  58.  
  59. list = delete_from_list(list, 5);
  60. display_list(list);
  61.  
  62. return 0;
  63. }
Success #stdin #stdout 0s 5424KB
stdin
Standard input is empty
stdout
list: 0x55646c5bc2e0, values: 1 2 3 4 5
list: 0x55646c5bc2c0, values: 2 3 4 5
list: 0x55646c5bc2c0, values: 2 4 5
list: 0x55646c5bc2c0, values: 2 4