C++ Program For Writing A Function To Delete A Linked List
Last Updated :
17 Aug, 2023
Algorithm For C++:
Iterate through the linked list and delete all the nodes one by one. The main point here is not to access the next of the current pointer if the current pointer is deleted.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
class Node
{
public :
int data;
Node* next;
};
void deleteList(Node** head_ref)
{
Node* current = *head_ref;
Node* next = NULL;
while (current != NULL)
{
next = current->next;
free (current);
current = next;
}
*head_ref = NULL;
}
void push(Node** head_ref, int new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int main()
{
Node* head = NULL;
push(&head, 1);
push(&head, 4);
push(&head, 1);
push(&head, 12);
push(&head, 1);
cout << "Deleting linked list" ;
deleteList(&head);
cout << "Linked list deleted" ;
}
|
Output:
Deleting linked list
Linked list deleted
Time Complexity: O(n)
Auxiliary Space: O(1)
Please refer complete article on Write a function to delete a Linked List for more details!
Share your thoughts in the comments
Please Login to comment...