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!
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!