Open In App

Write a function to delete a Linked List

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Algorithm For C/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.
In Java, Python, and JavaScript automatic garbage collection happens, so deleting a linked list is easy. Just need to change head to null.

You can delete the link list by following 3 methods:

  1. Delete from beginning
  2. Delete from the end
  3. Delete from middle

Delete from the beginning :

ALGORITHM:

  1. Store the address of the first node in a pointer. 
  2. move the head node to the next node
  3. dispose or free memory  of the pointer node 

C++




// Delete linkedlist from beginning
ListNode* X = head;
head = head->next;
delete X;


C




// Delete linkedlist from beginning
X=head;
head= head->next;
free(x);


Java




// Delete linkedlist from beginning
ListNode X = head;
head = head.next;
X = null;


Python3




# Delete linkedlist from beginning
X = head
head = head.next
X = None


C#




// Delete linkedlist from beginning
ListNode X = head;
head = head.next;
X = null;
 
// The code is contributed by Nidhi goel.


Javascript




<script>
 
// Delete linkedlist from beginning
ListNode X = head;
head = head.next;
X = null;
 
</script>


 

Delete the last node:

 

ALGORITHM:

  1. Traverse link list  to second last element
  2. Change its next pointer to null
  3. Free the memory of the last node.

C++




node* temp = head;
while (temp->next->next != NULL) {
  temp = temp->next;
}
temp->next = nullptr;


C




// Delete linkedlist from end
Struct node* temp=head ;
While(temp->next->next!=NULL)
{
  Temp= temp->next ;
}
Temp->next= NULL;


Java




ListNode temp = head;
while (temp.next.next != null) {
  temp = temp.next;
}
temp.next = null;


Python3




# Delete linkedlist from end
temp = head
while (temp.next and temp.next.next != None):
  temp = temp.next
temp.next = None


C#




ListNode temp = head;
while (temp.next.next != null) {
  temp = temp.next;
}
temp.next = null;
//this code is contributed by snehalsalokhe


Javascript




<script>
 
node temp = head;
while (temp.next.next != null) {
  temp = temp->next;
}
temp.next = nullptr;
 
</script>


Delete from the middle:

ALGORITHM:

  1. Store the address of the deleted node as a key node.
  2. Store the address of the preceding node in a pointer. Eg . P
  3. Store the address of a key node in the pointer variable  . eg . X
  4. Make the successor of the key node as the successor of the node pointed by p.
  5. Free node X.

C++




// Delete linkedlist from middle
for (int i = 2; i < position; i++) {
    if(temp->next != NULL) { temp = temp->next; }
}
temp->next = temp->next->next;
// This code is contributed by Yash Agarwal(yashagarwal2852002)


C




// Delete linkedlist from middle
for (int i = 2; i < position; i++) {
    If(temp->next != NULL) { Temp = temp->next; }
}
Temp->next = temp->next->next;


Java




// Delete linkedlist from middle
for (int i = 2; i < position; i++) {
  if (temp.next != null) {
    temp = temp.next;
  }
}
temp.next = temp.next.next;


Python3




# Delete linkedlist from middle
for i in range(2,position):
  if temp.next != None:
    temp = temp.next;
temp.next = temp.next.next;


C#




// Delete linkedlist from middle
int i = 2;
while (i < position) {
    if (temp.Next != null) {
        temp = temp.Next;
    }
    i++;
}
temp.Next = temp.Next.Next;
//this code is contributed by snehalsalokhe


Javascript




// delete linkedlist from middle
for(let i = 2; i<position; i++){
    if(temp.next != null)
    temp = temp.next;
}
temp.next = temp.next.next;
// This code is contributed by Kirti Agarwal(kirtiagarwal23121999)


Implementation: 

C++




// C++ program to delete a linked list
#include <bits/stdc++.h>
using namespace std;
 
/* Link list node */
class Node {
public:
    int data;
    Node* next;
};
 
/* Function to delete the entire linked list */
void deleteList(Node** head_ref)
{
 
    /* deref head_ref to get the real head */
    Node* current = *head_ref;
    Node* next = NULL;
 
    while (current != NULL)
    {
        next = current->next;
        free(current);
        current = next;
    }
 
    /* deref head_ref to affect the real head back
        in the caller. */
    *head_ref = NULL;
}
 
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(Node** head_ref, int new_data)
{
    /* allocate node */
    Node* new_node = new Node();
 
    /* put in the data */
    new_node->data = new_data;
 
    /* link the old list of the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
/* Driver code*/
int main()
{
    /* Start with the empty list */
    Node* head = NULL;
 
    /* Use push() to construct below list
    1->12->1->4->1 */
    push(&head, 1);
    push(&head, 4);
    push(&head, 1);
    push(&head, 12);
    push(&head, 1);
 
    cout << "Deleting linked list";
    deleteList(&head);
 
    cout << "\nLinked list deleted";
}
 
// This is code is contributed by rathbhupendra


C




// C program to delete a linked list
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
 
/* Link list node */
struct Node
{
    int data;
    struct Node* next;
};
 
/* Function to delete the entire linked list */
void deleteList(struct Node** head_ref)
{
   /* deref head_ref to get the real head */
   struct Node* current = *head_ref;
   struct Node* next;
 
   while (current != NULL)
   {
       next = current->next;
       free(current);
       current = next;
   }
   
   /* deref head_ref to affect the real head back
      in the caller. */
   *head_ref = NULL;
}
 
/* Given a reference (pointer to pointer) to the head
  of a list and an int, push a new node on the front
  of the list. */
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node =
            (struct Node*) malloc(sizeof(struct Node));
 
    /* put in the data  */
    new_node->data  = new_data;
    
    /* link the old list of the new node */
    new_node->next = (*head_ref);
    
    /* move the head to point to the new node */
    (*head_ref)    = new_node;
}
 
/* Driver program to test count function*/
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;
    
    /* Use push() to construct below list
     1->12->1->4->1  */
    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");
}


Java




// Java program to delete a linked list
import java.io.*;
 
class LinkedList {
    Node head; // head of the list
 
    /* Linked List node */
    class Node {
        int data;
        Node next;
        Node(int d)
        {
            data = d;
            next = null;
        }
    }
 
    /* Function deletes the entire linked list */
    void deleteList() { head = null; }
 
    /* Inserts a new Node at front of the list. */
    public void push(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                  Put in the data*/
        Node new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    public static void main(String[] args)
    {
        LinkedList llist = new LinkedList();
        /* Use push() to construct below list
           1->12->1->4->1  */
 
        llist.push(1);
        llist.push(4);
        llist.push(1);
        llist.push(12);
        llist.push(1);
 
        System.out.println("Deleting the list");
        llist.deleteList();
 
        System.out.println("Linked list deleted");
    }
}
// This code is contributed by Rajat Mishra


Python3




# Python3 program to delete all
# the nodes of singly linked list
 
# Node class
class Node:
 
    # Function to initialise the node object
    def __init__(self, data):
        self.data = data  # Assign data
        self.next = None  # Initialize next as null
 
# Constructor to initialize the node object
class LinkedList:
 
    # Function to initialize head
    def __init__(self):
        self.head = None
 
    def deleteList(self):
        # initialize the current node
        current = self.head
        while current:
            next_to_current = current.next  # move next node
 
            # delete the current node
            del current
 
            # set current equals prev node
            current = next_to_current
 
        # In python garbage collection happens
        # therefore, only
        # self.head = None
        # would also delete the link list
 
    # push function to add node in front of llist
    def push(self, new_data):
        # Allocate the Node &
        # Put in the data
        new_node = Node(new_data)
 
        # Make next of new Node as head
        new_node.next = self.head
 
        # Move the head to point to new Node
        self.head = new_node
 
# Use push() to construct below
# list 1-> 12-> 1-> 4-> 1
if __name__ == '__main__':
    llist = LinkedList()
    llist.push(1)
    llist.push(4)
    llist.push(1)
    llist.push(12)
    llist.push(1)
 
    print("Deleting linked list")
    llist.deleteList()
 
    print("Linked list deleted")


C#




// C# program to delete a linked list
using System;
     
public class LinkedList
{
    Node head; // head of the list
 
    /* Linked List node */
    class Node
    {
        public int data;
        public Node next;
        public Node(int d)
        {
            data = d; next = null;
        }
    }
 
    /* Function deletes the entire linked list */
    void deleteList()
    {
        head = null;
    }
 
    /* Inserts a new Node at front of the list. */
    public void push(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                Put in the data*/
        Node new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    // Driver code
    public static void Main(String [] args)
    {
        LinkedList llist = new LinkedList();
        /* Use push() to construct below list
        1->12->1->4->1 */
 
        llist.push(1);
        llist.push(4);
        llist.push(1);
        llist.push(12);
        llist.push(1);
 
        Console.WriteLine("Deleting the list");
        llist.deleteList();
 
        Console.WriteLine("Linked list deleted");
    }
}
 
// This code has been contributed by Rajput-Ji


Javascript




<script>
// javascript program to delete a linked list
var head; // head of the list
 
    /* Linked List node */
     class Node {
            constructor(val) {
                this.data = val;
                this.next = null;
            }
        }
 
    /* Function deletes the entire linked list */
    function deleteList() {
        head = null;
    }
 
    /* Inserts a new Node at front of the list. */
     function push(new_data) {
        /*
         * 1 & 2: Allocate the Node & Put in the data
         */
var new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
        /*
         * Use push() to construct below list 1->12->1->4->1
         */
 
        push(1);
        push(4);
        push(1);
        push(12);
        push(1);
 
        document.write("Deleting the list<br/>");
        deleteList();
 
        document.write("Linked list deleted");
 
// This code contributed by Rajput-Ji
</script>


Output

Deleting linked list
Linked list deleted

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads