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:
- Delete from beginning
- Delete from the end
- Delete from middle
Delete from the beginning :
ALGORITHM:
- Store the address of the first node in a pointer.Â
- move the head node to the next node
- dispose or free memory  of the pointer nodeÂ
C
// Delete linkedlist from beginningX=head;head= head->next;free(x); |
C++
// Delete linkedlist from beginningListNode* X = head;head = head->next;delete X; |
Java
// Delete linkedlist from beginningListNode X = head;head = head.next;X = null; |
Python3
# Delete linkedlist from beginningX = headhead = head.nextX = None |
Javascript
<script> Â
// Delete linkedlist from beginningListNode X = head;head = head.next;X = null;Â
</script> |
C#
// Delete linkedlist from beginningListNode X = head;head = head.next;X = null;Â
// The code is contributed by Nidhi goel. |
Â
Delete the last node:
ALGORITHM:
- Traverse link list  to second last element
- Change its next pointer to null
- Free the memory of the last node.
C
// Delete linkedlist from endStruct node* temp=head ;While(temp->next->next!=NULL){Â Â Temp= temp->next ;}Temp->next= NULL; |
C++
node* temp = head;while (temp->next->next != NULL) {Â Â temp = temp->next;}temp->next = nullptr; |
Python3
# Delete linkedlist from endtemp = headwhile (temp.next and temp.next.next != None):Â Â temp = temp.nexttemp.next = None |
Java
ListNode temp = head;while (temp.next.next != null) {Â Â temp = temp.next;}temp.next = null; |
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:
- Store the address of the deleted node as a key node.
- Store the address of the preceding node in a pointer. Eg . P
- Store the address of a key node in the pointer variable  . eg . X
- Make the successor of the key node as the successor of the node pointed by p.
- Free node X.
C
// Delete linkedlist from middlefor (int i = 2; i < position; i++) {Â Â Â Â If(temp->next != NULL) { Temp = temp->next; }}Temp->next = temp->next->next; |
C++
// Delete linkedlist from middlefor (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) |
Java
// Delete linkedlist from middlefor (int i = 2; i < position; i++) {Â Â if (temp.next != null) {Â Â Â Â temp = temp.next;Â Â }}temp.next = temp.next.next; |
Python3
# Delete linkedlist from middlefor i in range(2,position):Â Â if temp.next != None:Â Â Â Â temp = temp.next;temp.next = temp.next.next; |
C#
// Delete linkedlist from middleint 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 middlefor(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<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");} |
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 headof a list and an int, push a new node on the frontof 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 |
Java
// Java program to delete a linked listimport 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 objectclass 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.dataÂ
            # 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-> 1if __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")Â
Â
# This article is provided by Shrikant13 |
C#
// C# program to delete a linked listusing 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 listvar 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> |
Deleting linked list Linked list deleted
Time Complexity: O(n)Â
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
