Given only a pointer to a node to be deleted in a singly linked list, how do you delete it? - GeeksforGeeks

26 Jul, 2021
A simple solution is to traverse the linked list until you find the node you want to delete. But this solution requires a pointer to the head node which contradicts the problem statement. 
The fast solution is to copy the data from the next node to the node to be deleted and delete the next node. Something like this:
It is important to note that this approach will only work if it is guaranteed that the given pointer does not point to the last node. Because if it is the last node, then you don’t have a next node to copy the data from.
struct Node *temp  = node_ptr->next;
node_ptr->data  = temp->data;
node_ptr->next  = temp->next;
free(temp);
Below is the implementation of the above code:
C++
C
Java
Python3
C#
Javascript
// C++ program to del the node// in which only a single pointer// is known pointing to that node#include <assert.h>#include <bits/stdc++.h>using namespace std; /* Link list node */class Node {public:    int data;    Node* next;}; /* 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 off the new node */    new_node->next = (*head_ref);     /* move the head to point to the new node */    (*head_ref) = new_node;} void printList(Node* head){    Node* temp = head;    while (temp != NULL) {        cout << temp->data << " ";        temp = temp->next;    }} void deleteNode(Node* node_ptr){    // If the node to be deleted is the    // last node of linked list    if (node_ptr->next == NULL)    {        free(node_ptr);        // this will simply make the node_ptr NULL.        return;    }         // if node to be deleted is the first or    // any node in between the linked list.    Node* temp = node_ptr->next;    node_ptr->data = temp->data;    node_ptr->next = temp->next;    free(temp);} // Driver codeint 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 << "Before deleting \n";    printList(head);     /* I m deleting the head itself.        You can check for more cases */    deleteNode(head);     cout << "\nAfter deleting \n";    printList(head);    return 0;} // This code is contributed by rathbhupendra
// C++ program to del the node// in which only a single pointer// is known pointing to that node#include <assert.h>#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node {    int data;    struct Node* next;}; /* 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(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 off the new node */    new_node->next = (*head_ref);     /* move the head to point to the new node */    (*head_ref) = new_node;} void printList(struct Node* head){    struct Node* temp = head;    while (temp != NULL) {        printf("%d  ", temp->data);        temp = temp->next;    }} void deleteNode(struct Node* node_ptr){    // If the node to be deleted is the last    // node of linked list    if (node_ptr->next == NULL)    {        free(node_ptr);                // this will simply make the node_ptr NULL.        return;    }    struct Node* temp = node_ptr->next;    node_ptr->data = temp->data;    node_ptr->next = temp->next;    free(temp);} // Driver codeint 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 Before deleting \n");    printList(head);     /* I m deleting the head itself.        You can check for more cases */    deleteNode(head);     printf("\n After deleting \n");    printList(head);    getchar();}
// Java program to del the node in// which only a single pointer is// known pointing to that nodeclass LinkedList {     static Node head;    static class Node {         int data;        Node next;        Node(int d)        {            data = d;            next = null;        }    }     void printList(Node node)    {        while (node != null) {            System.out.print(node.data + " ");            node = node.next;        }    }     void deleteNode(Node node)    {        Node temp = node.next;        node.data = temp.data;        node.next = temp.next;        System.gc();    }     // Driver code    public static void main(String[] args)    {        LinkedList list = new LinkedList();        list.head = new Node(1);        list.head.next = new Node(12);        list.head.next.next = new Node(1);        list.head.next.next.next = new Node(4);        list.head.next.next.next.next = new Node(1);         System.out.println("Before Deleting ");        list.printList(head);         /* I m deleting the head itself.         You can check for more cases */        list.deleteNode(head);        System.out.println("");        System.out.println("After deleting ");        list.printList(head);    }} // This code has been contributed by Mayank Jaiswal
# A python3 program to delete# the node in which only a single pointer# is known pointing to that node # Linked list node  class Node():    def __init__(self):        self.data = None        self.next = None # 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  def push(head_ref, new_data):     # allocate node    new_node = Node()     # put in the data    new_node.data = new_data     # link the old list off the new node    new_node.next = head_ref     # move the head to point to the new node    head_ref = new_node     return head_ref  def printList(head):    temp = head    while(temp != None):        print(temp.data, end=' ')        temp = temp.next  def deleteNode(node_ptr):    temp = node_ptr.next    node_ptr.data = temp.data    node_ptr.next = temp.next  # Driver codeif __name__ == '__main__':     # Start with the empty list    head = None     # Use push() to construct below list    # 1->12->1->4->1    head = push(head, 1)    head = push(head, 4)    head = push(head, 1)    head = push(head, 12)    head = push(head, 1)     print("Before deleting ")    printList(head)     # I'm deleting the head itself.    # You can check for more cases    deleteNode(head)     print("\nAfter deleting")    printList(head) # This code is contributed by Yashyasvi Agarwal
// C# program to del the node in// which only a single pointer is// known pointing to that nodeusing System; public class LinkedList {     Node head;    public class Node {         public int data;        public Node next;        public Node(int d)        {            data = d;            next = null;        }    }     void printList(Node node)    {        while (node != null) {            Console.Write(node.data + " ");            node = node.next;        }    }     void deleteNode(Node node)    {        Node temp = node.next;        node.data = temp.data;        node.next = temp.next;    }     // Driver code    public static void Main()    {        LinkedList list = new LinkedList();        list.head = new Node(1);        list.head.next = new Node(12);        list.head.next.next = new Node(1);        list.head.next.next.next = new Node(4);        list.head.next.next.next.next = new Node(1);         Console.WriteLine("Before Deleting ");        list.printList(list.head);         /* I m deleting the head itself.        You can check for more cases */        list.deleteNode(list.head);        Console.WriteLine("");        Console.WriteLine("After deleting ");        list.printList(list.head);    }} /* This code contributed by PrinciRaj1992 */
<script>// javascript program to del the node in// which only a single pointer is// known pointing to that node     var head;     class Node{        constructor(val){            this.data = val;            this.next = null;        }    }     function printList(node){        while (node != null){            document.write(node.data + " ");            node = node.next;        }    }     function deleteNode(node) {        var temp = node.next;        node.data = temp.data;        node.next = temp.next;    }     // Driver code             head = new Node(1);        head.next = new Node(12);        head.next.next = new Node(1);        head.next.next.next = new Node(4);        head.next.next.next.next = new Node(1);         document.write("Before Deleting<br/> ");        printList(head);         /*         * I m deleting the head itself. You can check for more cases         */        deleteNode(head);        document.write("<br/>");        document.write("After deleting<br/> ");        printList(head); // This code is contributed by todaysgaurav</script>
Before deleting 
1 12 1 4 1 
After deleting 
12 1 4 1 
 
YouTubeGeeksforGeeks500K subscribersDelete a node whose pointer/reference is given in a singly linked list | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:28•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=yOjQS7rdkQQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
To make this solution work, we can mark the end node as a dummy node. But the programs/functions that are using this function should also be modified.Try this problem in a doubly-linked list.
 
princiraj1992
rathbhupendra
yashyasviagarwal
nidhi_biet
Piyushgupta12
todaysgaurav
karans15
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Doubly Linked List | Set 1 (Introduction and Insertion)
LinkedList in Java
Given a linked list which is sorted, how will you insert in sorted way
Implementing a Linked List in Java using Class
Insertion Sort for Singly Linked List
Queue - Linked List Implementation
Linked List vs Array
Circular Linked List | Set 2 (Traversal)
Split a Circular Linked List into two halves
Delete a node in a Doubly Linked List