Algorithm For C/C++: Iterate through the linked list and delete all the nodes one by one. Main point here is not to access next of the current pointer if current pointer is deleted.
In Java, automatic garbage collection happens, so deleting a linked list is easy. We just need to change head to null.
C Programming:
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
struct node
{
int data;
struct node* next;
};
void deleteList(struct node** head_ref)
{
struct node* current = *head_ref;
struct node* next;
while (current != NULL)
{
next = current->next;
free(current);
current = next;
}
*head_ref = NULL;
}
void push(struct node** head_ref, int new_data)
{
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int main()
{
struct node* head = NULL;
push(&head, 1);
push(&head, 4);
push(&head, 1);
push(&head, 12);
push(&head, 1);
printf("\n Deleting linked list");
deleteList(&head);
printf("\n Linked list deleted");
}
Output:
Deleting linked list
Linked list deleted
Time Complexity: O(n)
Auxiliary Space: O(1)
[ad type=”banner”]