fork download
  1. #include <iostream>
  2. #include <cstdio>
  3.  
  4. struct linked_list
  5. {
  6. int val;
  7. struct linked_list *next;
  8. };
  9.  
  10. using namespace std;
  11.  
  12. int release_list(struct linked_list* head)
  13. {
  14. struct linked_list *cur = head;
  15. while(cur != nullptr)
  16. {
  17. struct linked_list *next = cur->next;
  18. delete cur;
  19. cur = next;
  20. }
  21. return 0;
  22. }
  23.  
  24. void gen_list(const int gen_count, struct linked_list** head)
  25. {
  26. struct linked_list **cur = head;
  27. for(int i = 0; i < gen_count; i++)
  28. {
  29. (*cur) = (struct linked_list*)calloc(sizeof(struct linked_list), 1);
  30. (*cur)->next = nullptr;
  31. (*cur)->val = i;
  32. cur = &((*cur)->next);
  33. }
  34. }
  35.  
  36. void show_list(struct linked_list *head)
  37. {
  38. struct linked_list *cur = head;
  39. while(cur != nullptr)
  40. {
  41. printf("%d -> ", cur->val);
  42. cur = cur->next;
  43. }
  44. printf("\n");
  45. }
  46.  
  47. void del_node(int val, struct linked_list **head)
  48. {
  49. struct linked_list **curr = head; // We need a pointer to "a pointer to a linked-list"
  50. while((*curr)->val != val) // Dereference the pointer and compare the value, if value is we want to delete, the loop will stop.
  51. {
  52. curr = &((*curr)->next); // Walk to the next node, so we record the pointer to "a pointer to a linked-list"
  53. if((*curr) == nullptr) // If we walk to the end, return.
  54. return;
  55. }
  56. struct linked_list *delptr = *curr; // record the pointer we need to delete.
  57. *curr = (*curr)->next; // point the current "next pointer" to next pointer.
  58. delete(delptr); // and delete it!
  59. }
  60.  
  61. int main()
  62. {
  63. struct linked_list *list_node = nullptr;
  64. gen_list(10, &list_node);
  65. show_list(list_node);
  66. for(int i = 0; i < 5; i++)
  67. {
  68. del_node(i, &list_node);
  69. show_list(list_node);
  70. }
  71. printf("Cleaning...\n");
  72. release_list(list_node);
  73. return 0;
  74. }
  75.  
Success #stdin #stdout 0s 4368KB
stdin
Standard input is empty
stdout
0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 
2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 
3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 
4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 
5 -> 6 -> 7 -> 8 -> 9 -> 
Cleaning...