Advertisement
Guest User

Untitled

a guest
Feb 17th, 2020
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. // C++ program to delete a linked list
  2. #include <bits/stdc++.h>
  3.  
  4. using namespace std;
  5.  
  6.  
  7. /* Link list node */
  8.  
  9. class Node
  10. {
  11.  
  12. public:
  13.  
  14. int data;
  15.  
  16. Node* next;
  17. };
  18.  
  19.  
  20. /* Function to delete the entire linked list */
  21.  
  22. void deleteList(Node** head_ref)
  23. {
  24.  
  25.  
  26. /* deref head_ref to get the real head */
  27. Node* current = *head_ref;
  28. Node* next;
  29.  
  30.  
  31.  
  32. while (current != NULL)
  33. {
  34.  
  35. next = current->next;
  36.  
  37. free(current);
  38.  
  39. current = next;
  40. }
  41.  
  42.  
  43. /* deref head_ref to affect the real head back
  44.  
  45. in the caller. */
  46. *head_ref = NULL;
  47. }
  48.  
  49.  
  50. /* Given a reference (pointer to pointer) to the head
  51. of a list and an int, push a new node on the front
  52. of the list. */
  53.  
  54. void push(Node** head_ref, int new_data)
  55. {
  56.  
  57. /* allocate node */
  58.  
  59. Node* new_node = new Node();
  60.  
  61.  
  62.  
  63. /* put in the data */
  64.  
  65. new_node->data = new_data;
  66.  
  67.  
  68.  
  69. /* link the old list off the new node */
  70.  
  71. new_node->next = (*head_ref);
  72.  
  73.  
  74.  
  75. /* move the head to point to the new node */
  76.  
  77. (*head_ref) = new_node;
  78. }
  79.  
  80.  
  81. /* Driver code*/
  82.  
  83. int main()
  84. {
  85.  
  86. /* Start with the empty list */
  87.  
  88. Node* head = NULL;
  89.  
  90.  
  91.  
  92. /* Use push() to construct below list
  93.  
  94. 1->12->1->4->1 */
  95.  
  96. push(&head, 1);
  97.  
  98. push(&head, 4);
  99.  
  100. push(&head, 1);
  101.  
  102. push(&head, 12);
  103.  
  104. push(&head, 1);
  105.  
  106.  
  107.  
  108. cout << "Deleting linked list";
  109.  
  110. deleteList(&head);
  111.  
  112.  
  113.  
  114. cout << "\nLinked list deleted";
  115. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement