How to Delete a Linked List

Given a linked list, write a program to delete the linked list completely. That is we will be deleting all the nodes one by one

Example

Input : 6->16->15->50->1->23

Output : //It will be empty

Time Complexity : O(n)
Space Complexity : O(1)

Algorithm

1. Till the end of the linked list
2. Delete the head of the linked list, and make the head's next as the new head

C++ Program

#include <bits/stdc++.h>
using namespace std;

struct LL{
	int data;
	LL *next;	
};


void insertAtBeginning(struct LL**head,int dataToBeInserted)
{
	struct LL* curr=new LL;
		
		curr->data=dataToBeInserted;
		curr->next=NULL;
	
	if(*head==NULL)
			*head=curr; //if this is first node make this as head of list
		
	else
		{
			curr->next=*head; //else make the current (new) node's next point to head and make this new node a the head
			*head=curr;
		}
		
		//O(1) constant time
}

void deleteLL(struct LL**head)
{
	
	struct LL*temp=*head;
	while(temp!=NULL)
		{
			*head=temp->next; //after deletion of the given head , head will point to next of head
			delete temp;
			temp=*head;
		}
}


void display(struct LL**head)
{
	struct LL*temp=*head;
	while(temp!=NULL)
		{
			if(temp->next!=NULL)
			cout<<temp->data<<" ->";
			else
			cout<<temp->data;
			
			temp=temp->next; //move to next node
		}
		//O(number of nodes)
	cout<<endl;
}


int main()
{
	
	struct LL *head = NULL; //initial list has no elements
	insertAtBeginning(&head,6);
	insertAtBeginning(&head,16);
	insertAtBeginning(&head,15);
	insertAtBeginning(&head,50);
	insertAtBeginning(&head,1);
	insertAtBeginning(&head,23);
	cout<<"Initial List is :-\n";
	display(&head);
	
	deleteLL(&head);
	cout<<"\nAfter the deletion of whole linked list the list becomes : -\n";
	display(&head);
	
	return 0;
}
Try It


Next > < Prev
Scroll to Top