Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?
Next article icon

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
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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:

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 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
// C code to delete node value  #include <stdio.h> #include <stdlib.h>  struct Node {     int data;     struct Node* next; };  // Function to delete a node value when  // only a pointer to that node is given void deleteNode(struct Node* delNode ) {          // Ensure the node to be deleted is not the last node     if (delNode  == NULL || delNode ->next == NULL) {         return;       }      // Copy data from the next node into the current node     struct 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)     free(temp); }  void printList(struct Node* head) {     struct Node* curr = head;     while (curr != NULL) {         printf("%d ", curr->data);         curr = curr->next;     }     printf("\n"); }  struct Node* createNode(int x) {     struct Node* new_node         = (struct Node*)malloc(sizeof(struct Node));     new_node->data = x;     new_node->next = NULL;     return new_node; }  int main() {          // Creating a linked list: 4 -> 5 -> 6 -> 7 -> 8      struct Node* head = createNode(4);     head->next = createNode(5);     head->next->next = createNode(6);     head->next->next->next = createNode(7);     head->next->next->next->next = createNode(8);      deleteNode(head);      printList(head);      return 0; } 
Java
// Java code to delete node value  class Node {     int data;     Node next;      Node(int val) {         data = val;         next = null;     } }  class GfG {          // Function to delete a node value when      // only a pointer to that node is given     static void deleteNode(Node delNode) {                  // Ensure the node to be deleted is not the last node         if (delNode == null || delNode.next == null) {             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)         temp.next = null;     }      static void printList(Node head) {         Node curr = head;         while (curr != null) {             System.out.print(curr.data + " ");             curr = curr.next;         }         System.out.println();     }      public static void main(String[] args) {                  // 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);     } } 
Python
# Python code to delete node value  class Node:     def __init__(self, data):         self.data = data         self.next = None  # Function to delete a node value when  # only a pointer to that node is given def deleteNode(delNode):          # Ensure the node to be deleted is not the last node     if delNode is None or delNode.next is None:         return      # Copy data from the next node into the current 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)     del temp  def printList(head):     curr = head     while curr:         print(curr.data, end=" ")         curr = curr.next     print()  if __name__ == "__main__":          # Creating a linked list: 4 -> 5 -> 6 -> 7 -> 8     head = Node(4)     head.next = Node(5)     head.next.next = Node(6)     head.next.next.next = Node(7)     head.next.next.next.next = Node(8)      deleteNode(head)      printList(head) 
C#
// C# code to delete node value  using System;  class Node {     public int data;     public Node next;      public Node(int val) {         data = val;         next = null;     } }  class GfG {          // Function to delete a node value when      // only a pointer to that node is given     static void deleteNode(Node delNode) {                  // Ensure the node to be deleted is not the last node         if (delNode == null || delNode.next == null) {             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)         temp.next = null;     }      static void printList(Node head) {         Node curr = head;         while (curr != null) {             Console.Write(curr.data + " ");             curr = curr.next;         }         Console.WriteLine();     }      static void Main(string[] args) {                  // 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);     } } 
JavaScript
// Javascript code to delete node value  class Node {     constructor(data) {         this.data = data;         this.next = null;     } }  // Function to delete a node value when  // only a pointer to that node is given function deleteNode(delNode) {          // Ensure the node to be deleted is not the last node     if (delNode === null || delNode.next === null) {         return;     }      // Copy data from the next node into the current node     const 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)     temp.next = null; }  function printList(head) {     let curr = head;     while (curr !== null) {         console.log(curr.data + " ");         curr = curr.next;     }     console.log(); }  // Creating a linked list: 4 -> 5 -> 6 -> 7 -> 8 let 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); 

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.

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

K

kartik
Improve
Article Tags :
  • Linked List
  • DSA
  • Linked Lists
  • loop
  • Microsoft
  • Amazon
  • Samsung
  • Goldman Sachs
  • Visa
  • Kritikal Solutions
Practice Tags :
  • Amazon
  • Goldman Sachs
  • Kritikal Solutions
  • Microsoft
  • Samsung
  • Visa
  • Linked List

Similar Reads

    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
    6 min read
    Delete all occurrences of a given key in a doubly linked list
    Given a doubly linked list and a key x. The problem is to delete all occurrences of the given key x from the doubly linked list. Examples: Algorithm: delAllOccurOfGivenKey(head_ref, x) if head_ref == NULL return Initialize current = head_ref Declare next while current != NULL if current->data ==
    14 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<->3Input: LinkedList: 1<->2<->3, pos = 1Output: LinkedList: 2<->
    9 min read
    Program to delete all even nodes from a Singly Linked List
    Given a singly linked list containing N nodes, the task is to delete all the even nodes from the list. Examples: Input: LL = 1 -> 4 -> 3 -> 18 -> 19 Output: 1 -> 3 -> 19Input: LL = 5 -> 3 -> 6 -> 8 -> 4 -> 1 -> 2 -> 9 Output: 5 -> 3 -> 1 -> 9 Approach
    15+ 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
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences