C Program For Writing A Function To Delete A Linked List
Last Updated :
21 Mar, 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<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 ( "Deleting linked list" );
deleteList(&head);
printf ( "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!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...