Open In App

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

Last Updated : 29 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given a pointer to a node to be deleted, delete the node. Note that we don’t have a pointer to the head node.

Examples:

Input: list = 10 -> 20 -> 4 -> 30, delNode = 20
Output: 10 -> 4 -> 30
Explanation: Node with value 20 is deleted.

Input: list = 1 -> 2, delNode = 1
Output: 2
Explanation: Node with value 1 is deleted.

Approach:

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 idea is to copy the data from the next node into the given node and then deleting the next node.

Below is the implementation of the above approach: 

C++
// C++ code to delete node value

#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;

    Node(int val) {
        data = val;
        next = nullptr;
    }
};

// Function to delete a node value when 
// only a pointer to that node is given
void deleteNode(Node* delNode ) {
    
    // Ensure the node to be deleted is not the last node
    if (delNode  == nullptr || delNode ->next == nullptr) {
        return;  
    }

    // Copy data from the next node into the current node
    Node* temp = delNode ->next;
    delNode ->data = temp->data;

    // Link current node to the node after the next node
    delNode ->next = temp->next;

    // Delete the next node (the one whose data was copied)
    delete temp;
}

void printList(Node* head) {
    Node* curr = head;
    while (curr != nullptr) {
        cout << curr->data << " ";
        curr = curr->next;
    }
    cout << endl;
}

int main() {
    
    // Creating a linked list: 4 -> 5 -> 6 -> 7 -> 8
    Node* head = new Node(4);
    head->next = new Node(5);
    head->next->next = new Node(6);
    head->next->next->next = new Node(7);
    head->next->next->next->next = new Node(8);

    deleteNode(head);

    printList(head);

    return 0;
}
C Java Python C# JavaScript

Output
5 6 7 8 

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

Note: The described method of copying data from the next node works well for all nodes except the last one. To delete the last node, we need either:

  • A pointer/reference to the previous node,
  • A pointer/reference to the head node to traverse and find the previous node.


Similar Reads

three90RightbarBannerImg