The Wayback Machine - https://web.archive.org/web/20241118231826/https://www.geeksforgeeks.org/delete-a-node-from-linked-list-without-head-pointer/
Open In App

Delete a Node from linked list without head pointer

Last Updated : 16 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

You are given a singly linked list and pointer which is pointing to the node which is required to be deleted. Any information about the head pointer or any other node is not given. You need to write a function to delete that node from the linked list. Your function will take only one argument, i.e., a pointer to the node which is to be delete

Note: No head reference is given to you. It is guaranteed that the node to be deleted is not the last node:

A linked list is built as: 

Definition of each node is as follows: 
struct Node {
    int data;
    struct Node* next;
}; 

 

Examples: 

Consider below LL for given examples:

Input: C (a pointer to C)
Output: A–>B–>D–>E–>F

Input: A (a pointer to A)
Output: B–>D–>E–>F

Recommended Practice

Approach: To solve the problem follow the below idea:

  • Why conventional deletion method would fail here?
    It would be a simple deletion problem from the singly linked list if the head pointer was given because for deletion you must know the previous node and you can easily reach there by traversing from the head pointer. Conventional deletion is impossible without knowledge of the previous node of a node that needs to be deleted. 
  • How to delete the node when you dont have the head pointer?
    The trick here is we can copy the data of the next node to the data field of the current node to be deleted. Then we can move one step forward. Now our next has become the current node and the current has become the previous node. Now we can easily delete the current node by conventional deletion methods. 

Illustration of the above approach:

For example, suppose we need to delete B and a pointer to B is given

If we had a pointer to A, we could have deleted B easily. 
But here we will copy the data field of C to the data field of B. Then we will move forward. 

Now we are at C and we have a pointer to B i.e. the previous pointer. So we will delete C. 

That’s how node B will be deleted. 

Below image is a dry run of the above approach:

Below is the implementation of the above approach:

C++




// C++ program to delete a node
#include <bits/stdc++.h>
using namespace std;
  
/* Link list node */
struct Node {
    int data;
    struct Node* next;
};
  
// Function to delete the node without head
void deleteNodeWithoutHead(struct Node* pos)
{
    if (pos == NULL) // If linked list is empty
        return;
    else {
  
        if (pos->next == NULL) {
            printf("This is last node, require head, can't "
                   "be freed\n");
            return;
        }
  
        struct Node* temp = pos->next;
  
        // Copy data of the next node to current node
        pos->data = pos->next->data;
  
        // Perform conventional deletion
        pos->next = pos->next->next;
  
        free(temp);
    }
}
  
// Function to print the linked list
void print(Node* head)
{
    Node* temp = head;
    while (temp) {
        cout << temp->data << " -> ";
        temp = temp->next;
    }
  
    cout << "NULL";
}
  
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct 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 */
    struct Node* head = NULL;
  
    // create linked 35->15->4->20
    push(&head;, 20);
    push(&head;, 4);
    push(&head;, 15);
    push(&head;, 35);
    cout << "Initial Linked List: \n";
    print(head);
    cout << endl << endl;
  
    // Delete 15 without sending head
    Node* del = head->next;
  
    // Function call
    deleteNodeWithoutHead(del);
  
    // Print the final linked list
    cout << "Final Linked List after deletion of 15:\n";
    print(head);
  
    return 0;
  
    // This code has been contributed by Striver
}


Java




// Java Program to delete a node
  
class Node{
  int data;
  Node next;
  Node(int val){
    data = val;
    next = null;
  }
}
  
class LinkedList{
  Node head;
  
  // Function to delete the node without head
  void deleteNodeWithoutHead(Node pos){
    if(pos == null) // If linked list is empty
      return;
    else{
      if(pos.next == null){
        System.out.println("This is last node, require head, can't be freed\n");
        return;
      }
    }
    // copy data of the next node to current node
    pos.data = pos.next.data;
  
    // perform conventional deletion
    pos.next = pos.next.next;
  }
  
  public void push(int new_data){
    // allocate node and put in the data
    Node new_node = new Node(new_data);
  
    // link the old list of the new node
    new_node.next = head;
  
    // move the head to point to the new node
    head = new_node;
  }
  
  public void printList(){
    Node temp = head;
    while(temp != null){
      System.out.print(temp.data + "->");
      temp = temp.next;
    }
    System.out.println("NULL\n");
  }
  
  public static void main(String args[]){
    LinkedList llist = new LinkedList();
  
    // create linked list 35->15->4->20
    llist.push(20);
    llist.push(4);
    llist.push(15);
    llist.push(35);
  
    System.out.println("Initial Linked List : ");
    llist.printList();
  
    // Delete 15 without sending head
    Node del = llist.head.next;
  
    // Function call
    llist.deleteNodeWithoutHead(del);
  
    // Print the final Linked List
    System.out.println("Final Linked List after deletion of 15 : ");
    llist.printList();
  }
}
  
// This code is contributed by Yash Agarwal(yashagarwal2852002)


Python3




class Node:
    def __init__(self, val):
        self.data = val
        self.next = None
  
class LinkedList:
    def __init__(self):
        self.head = None
  
    # Function to delete the node without head
    def delete_node_without_head(self, pos):
        if pos is None:  # If linked list is empty
            return
        elif pos.next is None:
            print("This is last node, require head, can't be freed\n")
            return
  
        # copy data of the next node to current node
        pos.data = pos.next.data
  
        # perform conventional deletion
        pos.next = pos.next.next
  
    def push(self, new_data):
        # allocate node and put in the data
        new_node = Node(new_data)
  
        # link the old list of the new node
        new_node.next = self.head
  
        # move the head to point to the new node
        self.head = new_node
  
    def print_list(self):
        temp = self.head
        while temp is not None:
            print(temp.data, end='->')
            temp = temp.next
        print("NULL\n")
  
if __name__ == '__main__':
    llist = LinkedList()
  
    # create linked list 35->15->4->20
    llist.push(20)
    llist.push(4)
    llist.push(15)
    llist.push(35)
  
    print("Initial Linked List : ")
    llist.print_list()
  
    # Delete 15 without sending head
    del_node = llist.head.next
  
    # Function call
    llist.delete_node_without_head(del_node)
  
    # Print the final Linked List
    print("Final Linked List after deletion of 15 : ")
    llist.print_list()
  
# This code has been contributed by Mayank Bohra


C#




// C# Program to delete a node
  
using System;
  
class Node
{
public int data;
public Node next;
  public Node(int val)
{
    data = val;
    next = null;
}
}
  
class LinkedList
{
public Node head;
  public LinkedList()
{
    head = null;
}
  
// Function to delete the node without head
public void delete_node_without_head(Node pos)
{
    if (pos == null)  // If linked list is empty
    {
        return;
    }
    else if (pos.next == null)
    {
        Console.WriteLine("This is last node, require head, can't be freed\n");
        return;
    }
  
    // copy data of the next node to current node
    pos.data = pos.next.data;
  
    // perform conventional deletion
    pos.next = pos.next.next;
}
  
public void push(int new_data)
{
    // allocate node and put in the data
    Node new_node = new Node(new_data);
  
    // link the old list of the new node
    new_node.next = head;
  
    // move the head to point to the new node
    head = new_node;
}
  
public void print_list()
{
    Node temp = head;
    while (temp != null)
    {
        Console.Write(temp.data + "->");
        temp = temp.next;
    }
    Console.WriteLine("NULL\n");
}
}
  
class Program
{
static void Main(string[] args)
{
LinkedList llist = new LinkedList();
    // create linked list 35->15->4->20
    llist.push(20);
    llist.push(4);
    llist.push(15);
    llist.push(35);
  
    Console.WriteLine("Initial Linked List : ");
    llist.print_list();
  
    // Delete 15 without sending head
    Node del_node = llist.head.next;
  
    // Function call
    llist.delete_node_without_head(del_node);
  
    // Print the final Linked List
    Console.WriteLine("Final Linked List after deletion of 15 : ");
    llist.print_list();
}
}
  
//This code is contributed by shivamsharma215


Javascript




class Node{
      
    constructor(val){
        this.data = val;
        this.next = null;
    }
}
  
class LinkedList{
      
    constructor(){
        this.head = null;
    }
  
    // Function to delete the node without head
    delete_node_without_head(pos){
        if(pos == null) //  If linked list is empty
            return;
        else if(pos.next == null){
            console.log("This is last node, require head, can't be freed\n");
            return;
        }
  
        // copy data of the next node to current node
        pos.data = pos.next.data;
  
        // perform conventional deletion
        pos.next = pos.next.next;
    }
  
    push(new_data){
        // allocate node and put in the data
        let new_node = new Node(new_data);
  
        // link the old list of the new node
        new_node.next = this.head;
  
        // move the head to point to the new node
        this.head = new_node;
    }
  
    print_list(){
          
        let temp = this.head;
        while(temp != null){
            console.log(temp.data + "->");
            temp = temp.next;
        }
        console.log("NULL \n\n");
    }
      
  
}
  
let llist = new LinkedList();
  
// create linked list 35->15->4->20
llist.push(20);
llist.push(4);
llist.push(15);
llist.push(35);
  
console.log("Initial Linked List : \n");
llist.print_list();
  
// Delete 15 without sending head
let del_node = llist.head.next;
  
// Function call
llist.delete_node_without_head(del_node);
  
// Print the final Linked List
console.log("Final Linked List after deletion of 15 : \n");
llist.print_list();
  
// This code has been contributed by Nidhi goel.


Output

Initial Linked List: 
35 -> 15 -> 4 -> 20 -> NULL

Final Linked List after deletion of 15:
35 -> 4 -> 20 -> NULL

Time complexity: O(1) since performing constant operations and modifying only a single pointer to delete node
Auxiliary Space: O(1)

Please see Given only a pointer to a node to be deleted in a singly linked list, how do you delete it for more details and complete implementation.



Previous Article
Next Article

Similar Reads

Delete Without Head Pointer using JavaScript
The objective is to remove a node in a JavaScript singly linked list without having a direct reference to the head node. This entails making changes to the node that will be removed without actually using the head pointer. Below are the approaches to deleting a node without a head pointer using JavaScript: Table of Content Copy Data and Adjust Poin
6 min read
How to write C functions that modify head pointer of a Linked List?
Consider simple representation (without any dummy node) of Linked List. Functions that operate on such Linked lists can be divided into two categories: 1) Functions that do not modify the head pointer: Examples of such functions include, printing a linked list, updating data members of nodes like adding given a value to all nodes, or some other ope
4 min read
Go Pointer to Pointer (Double Pointer)
Prerequisite: Pointers in Go Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. A pointer is a special variable so it can point to a variable of any type even to a pointer. Basically, this looks like a chain of pointers. When we define a pointer to pointer then the first pointe
4 min read
C++ Pointer To Pointer (Double Pointer)
In C++ a Pointer is a variable that is used to store the memory address of other variables. It is a variable that points to a data type (like int or string) of the same type and is created with the * operator. Syntax of a Pointer in C++: data_type_of_pointer *name_of_variable = & normal_variable; What is a Pointer to a Pointer or Double Pointer
4 min read
C - Pointer to Pointer (Double Pointer)
Prerequisite: Pointers in C The pointer to a pointer in C is used when we want to store the address of another pointer. The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double-pointers. We can use a pointer to a pointer to cha
5 min read
Number of sequences which has HEAD at alternate positions to the right of the first HEAD
Given that a coin is tossed N times. The task is to find the total number of the sequence of tosses such that after the first head from left, all the alternating positions to the right of it are occupied by the head only. The positions except the alternating position can be occupied by any of head or tail. For example, if you are tossing a coin 10
6 min read
Delete a Node in a Singly Linked List with Only a Pointer
Given only a pointer to a node to be deleted in a singly linked list. The task is to delete that node from the list. Note: The given pointer does not point to the last node of the linked list. Examples: Input: LinkedList: 1->2->3->4->5, delete_ptr = 2Output: LinkedList: 1->3->4->5 Input: LinkedList: 1->2->3->4->5, d
6 min read
Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?
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 = 20Output: 10 -> 4 -> 30Explanation: Node with value 20 is deleted. Input: list = 1 -> 2, delNode = 1Output: 2Explanation: Node with value 1 is deleted. Approach: A sim
7 min read
How to create a pointer to another pointer in a linked list?
In this article we cover how to create a pointer to another pointer in a linked list, it can be singly, doubly, or circularly. What is Linked List: A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image: Singly
7 min read
Find kth node from Middle towards Head of a Linked List
Given a Linked List and a number K. The task is to print the value of the K-th node from the middle towards the beginning of the List. If no such element exists, then print "-1". Note: The position of the middle node is: (n/2)+1, where n is the total number of nodes in the list. Examples: Input : List is 1->2->3->4->5->6->7 K= 2 O
14 min read
Make middle node head in a linked list
Given a singly linked list, find middle of the linked list and set middle node of the linked list at beginning of the linked list. Examples: Input : 1 2 3 4 5 Output : 3 1 2 4 5 Input : 1 2 3 4 5 6 Output : 4 1 2 3 5 6 The idea is to first find middle of a linked list using two pointers, first one moves one at a time and second one moves two at a t
10 min read
Javascript Program For Making Middle Node Head In A Linked List
Given a singly linked list, find middle of the linked list and set middle node of the linked list at beginning of the linked list. Examples: Input: 1 2 3 4 5 Output: 3 1 2 4 5Input: 1 2 3 4 5 6Output: 4 1 2 3 5 6 The idea is to first find middle of a linked list using two pointers, first one moves one at a time and second one moves two at a time. W
3 min read
Delete multiple occurrences of key in Linked list using double pointer
Given a singly linked list, delete all occurrences of a given key in it. For example, consider the following list. Input: 2 -> 2 -> 4 -> 3 -> 2 Key to delete = 2Output: 4 -> 3 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.This is mainly an alternative of this post which deletes multiple occurrence
6 min read
Print Head node of every node in Binary Tree
Given the root of the Binary Tree. Print the parent node of each node in the given Binary Tree. Examples : Input: Binary Tree = {1, 2, 3, 4, 5, NULL, NULL, NULL, 6} Output : The Head Node of 6 is 4 The Head Nodeof 5 is 2The Head Node of 4 is 2The Head Node of 3 is 1 The Head Node of 2 is 1 Explanation: Clearly By Observing Image we are finding pare
7 min read
Sorted insert in a doubly linked list with head and tail pointers
A Doubly linked list is a linked list that consists of a set of sequentially linked records called nodes. Each node contains two fields that are references to the previous and to the next node in the sequence of nodes. The task is to create a doubly linked list by inserting nodes such that list remains in ascending order on printing from left to ri
10 min read
Point arbit pointer to greatest value right side node in a linked list
Given singly linked list with every node having an additional “arbitrary” pointer that currently points to NULL. We need to make the “arbitrary” pointer to the greatest value node in a linked list on its right side. A Simple Solution is to traverse all nodes one by one. For every node, find the node which has the greatest value on the right side an
15+ min read
Point to next higher value node in a linked list with an arbitrary pointer
Given singly linked list with every node having an additional "arbitrary" pointer that currently points to NULL. Need to make the "arbitrary" pointer point to the next higher value node. We strongly recommend to minimize your browser and try this yourself first A Simple Solution is to traverse all nodes one by one, for every node, find the node whi
15+ min read
Javascript Program For Pointing Arbit Pointer To Greatest Value Right Side Node In A Linked List
Given singly linked list with every node having an additional “arbitrary” pointer that currently points to NULL. We need to make the “arbitrary” pointer to the greatest value node in a linked list on its right side. A Simple Solution is to traverse all nodes one by one. For every node, find the node which has the greatest value on the right side an
5 min read
Javascript Program For Pointing To Next Higher Value Node In A Linked List With An Arbitrary Pointer
Given singly linked list with every node having an additional "arbitrary" pointer that currently points to NULL. Need to make the "arbitrary" pointer point to the next higher-value node. We strongly recommend to minimize your browser and try this yourself first A Simple Solution is to traverse all nodes one by one, for every node, find the node whi
4 min read
Output of the Program | Pointer to a Constant or Constant Pointer?
Predict the output of the below program. C/C++ Code #include <iostream> using namespace std; int main() { int x = 5; int * const ptr = &x; ++(*ptr); cout << x; return 0; } // This code is contributed by sarajadhav12052009 C/C++ Code #include <stdio.h> int main() { int x = 5; int * const ptr = &x; ++(*ptr); printf("%d
2 min read
Difference between Dangling pointer and Void pointer
Dangling pointer: A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer. There are three different ways where Pointer acts as a dangling pointer: By deallocating memoryFunction CallWhen the variable goes out of scope Void pointer: Void pointer is a specific pointer type – void * – a pointer that point
2 min read
Pointer to Pointer in Objective-C
Pointers in Objective-C are a powerful and essential concept for any programmer to master. Pointers allow you to manipulate data stored in memory directly and are used to store the address of a variable. Pointer-to-pointer also known as a double pointer, is a type of pointer that holds the address of another pointer. The pointer-to-pointer concept
4 min read
Pointer to an Array | Array Pointer
Prerequisite: Pointers Introduction Consider the following program: [GFGTABS] C #include<stdio.h> int main() { int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr; printf("%p\n", ptr); return 0; } [/GFGTABS]In the above program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer th
9 min read
Delete a given node in Linked List under given constraints
Given a Singly Linked List, write a function to delete a given node. Your function must follow following constraints: 1) It must accept a pointer to the start node as the first parameter and node to be deleted as the second parameter i.e., a pointer to head node is not global. 2) It should not return a pointer to the head node. 3) It should not acc
11 min read
Delete every Kth node from circular linked list
Delete every kth node from a circular linked list until only one node is left. Also, print the intermediate lists. Examples: Input : n=4, k=2, list = 1->2->3->4 Output : 1->2->3->4->1 1->2->4->1 2->4->2 2->2 Input : n=9, k=4, list = 1->2->3->4->5->6->7->8->9 Output : 1->2->3->4
13 min read
Recursive function to delete k-th node from linked list
Given a singly linked list, delete a node at the kth position without using the loop. Examples: Input : list = 9->8->3->5->2->1 k = 4 Output : 9->8->3->2->1 Input : list = 0->0->1->6->2->3 k = 3 Output : 0->0->6->2->3 We recursively reduce the value of k. When k reaches 1, we delete the current
6 min read
Delete Nth node from the end of the given linked list
Given a linked list and an integer N, the task is to delete the Nth node from the end of the given linked list. Examples: Input: 2 -> 3 -> 1 -> 7 -> NULL, N = 1 Output: The created linked list is: 2 3 1 7 The linked list after deletion is: 2 3 1 Input: 1 -> 2 -> 3 -> 4 -> NULL, N = 4 Output: The created linked list is: 1 2 3
13 min read
Delete a Doubly Linked List node at a given position
Given a doubly linked list and a position pos, the task is to delete the node at the given position from the beginning of Doubly Linked List. Input: LinkedList: 1<->2<->3, pos = 2Output: LinkedList: 1<->3 Input: LinkedList: 1<->2<->3, pos = 1Output: LinkedList: 2<->3 To delete a node at a specific position in dou
9 min read
Delete a Linked List node at a given position
Given a singly linked list and a position (1-based indexing), the task is to delete a linked list node at the given position. Note: Position will be valid (i.e, 1 <= position <= linked list length) Example: Input: position = 2, Linked List = 8->2->3->1->7Output: Linked List = 8->3->1->7 Input: position = 1, Linked List =
8 min read
XOR linked list- Remove first node of the linked list
Given an XOR linked list, the task is to remove the first node of the XOR linked list. Examples: Input: XLL = 4 < – > 7 < – > 9 < – > 7 Output: 7 < – > 9 < – > 7 Explanation: Removing the first node of the XOR linked list modifies XLL to 7 < – > 9 < – > 7 Input: XLL = NULL Output: List Is Empty Approach: Th
11 min read
three90RightbarBannerImg