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:
Delete last occurrence of an item from linked list
Next article icon

Delete last occurrence of an item from linked list

Last Updated : 20 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a singly linked list and a key, the task is to delete the last occurrence of that key in the linked list.

Examples: 

Input: head: 1 -> 2 -> 3 ->1 -> 4 -> NULL, key = 1 
Output: 1 -> 2 -> 3 -> 4 -> NULL

Delete-last-occurrence-of-an-item-from-linked-list-1


Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> NULL , key = 3
Output: 1 -> 2 -> 4 -> 5 -> NULL

Delete-last-occurrence-of-an-item-from-linked-list-2

Approach:

The idea is to traverse the linked list from beginning to end. While traversing, keep track of last occurrence key node and previous node of that key. After traversing the complete list, delete the last occurrence of that key.  

Follow the steps below to solve the problem:

  • Initialize Pointer curr points to head, last, lastPrev and prev to NULL.
  • Traverse the List until curr is not NULL:
    • If curr->data == key, update lastPrev to the prev and last to curr.
    • Move prev pointer to curr and curr to the next node.
  • Delete Last Occurrence (if key was found then last is not null):
    • If lastPrev is not null, adjust lastPrev->next = last->next to skip last.
    • If last is the head, update the head to last->next.
C++
// C++ program to delete last occurrence  // of key in singly linked list  #include <iostream> using namespace std;  class Node { public:     int data;     Node* next;      Node(int x) {         data = x;         next = nullptr;     } };  // Function to delete the last occurrence  // of a key in the linked list Node* deleteLastOccurrence(Node* head, int key) {     Node *last = nullptr, *lastPrev = nullptr;     Node *curr = head, *prev = nullptr;      // Traverse the list to find the last    	// occurrence of the key     while (curr != nullptr) {         if (curr->data == key) {             lastPrev = prev;             last = curr;         }         prev = curr;         curr = curr->next;     }      // If the key was found     if (last != nullptr) {                	// If last occurrence is not the head         if (lastPrev != nullptr) {             lastPrev->next = last->next;         } else {                        // If last occurrence is the head,            	// move head to next node             head = head->next;         }         delete last;     }      return head; }  void print(Node* curr) {     while (curr != nullptr) {         cout << curr->data << " ";         curr = curr->next;     }     cout << endl; }  int main() {        // Create a hard-coded linked list:     // 1 -> 2 -> 2 -> 4 -> 2     Node* head = new Node(1);     head->next = new Node(2);     head->next->next = new Node(2);     head->next->next->next = new Node(4);     head->next->next->next->next = new Node(2);      int key = 2;     head = deleteLastOccurrence(head, key);     print(head);     return 0; } 
C
// C program to delete last occurrence  // of key in singly linked list  #include <stdio.h> #include <stdlib.h>  struct Node {     int data;     struct Node* next; };  // Function to delete the last occurrence // of a key in the linked list struct Node* deleteLastOccurrence(struct Node* head, int key) {     struct Node *last = NULL, *lastPrev = NULL;     struct Node *curr = head, *prev = NULL;      // Traverse the list to find the last     // occurrence of the key     while (curr != NULL) {         if (curr->data == key) {             lastPrev = prev;             last = curr;         }         prev = curr;         curr = curr->next;     }      // If the key was found     if (last != NULL) {          // If last occurrence is not the head         if (lastPrev != NULL) {             lastPrev->next = last->next;         } else {              // If last occurrence is the head,             // move head to next node             head = head->next;         }         free(last);     }      return head; }  void print(struct Node* curr) {     while (curr != NULL) {         printf("%d ", curr->data);         curr = curr->next;     }     printf("\n"); }  struct Node* createNode(int new_data) {     struct Node* newNode =        (struct Node*)malloc(sizeof(struct Node));     newNode->data = new_data;     newNode->next = NULL;     return newNode; }  int main() {        // Create a hard-coded linked list:     // 1 -> 2 -> 2 -> 4 -> 2     struct Node* head = createNode(1);     head->next = createNode(2);     head->next->next = createNode(2);     head->next->next->next = createNode(4);     head->next->next->next->next = createNode(2);      int key = 2;     head = deleteLastOccurrence(head, key);     print(head);     return 0; } 
Java
// Java program to delete last occurrence  // of key in singly linked list  class Node {     int data;     Node next;      Node(int x) {         data = x;         next = null;     } }  class GfG {        // Function to delete the last occurrence      // of a key in the linked list     static Node deleteLastOccurrence(Node head, int key) {         Node last = null, lastPrev = null;         Node curr = head, prev = null;          // Traverse the list to find the last          // occurrence of the key         while (curr != null) {             if (curr.data == key) {                 lastPrev = prev;                 last = curr;             }             prev = curr;             curr = curr.next;         }          // If the key was found         if (last != null) {              // If last occurrence is not the head             if (lastPrev != null) {                 lastPrev.next = last.next;             } else {                  // If last occurrence is the head,                  // move head to next node                 head = head.next;             }         }          return head;     }      static void print(Node curr) {         while (curr != null) {             System.out.print(curr.data + " ");             curr = curr.next;         }         System.out.println();     }      public static void main(String[] args) {                // Create a hard-coded linked list:         // 1 -> 2 -> 2 -> 4 -> 2         Node head = new Node(1);         head.next = new Node(2);         head.next.next = new Node(2);         head.next.next.next = new Node(4);         head.next.next.next.next = new Node(2);          int key = 2;         head = deleteLastOccurrence(head, key);         print(head);     } } 
Python
# Python program to delete last occurrence  # of key in singly linked list  class Node:     def __init__(self, x):         self.data = x         self.next = None  # Function to delete the last occurrence # of a key in the linked list def deleteLastOccurrence(head, key):     last = None     lastPrev = None     curr = head     prev = None      # Traverse the list to find the last     # occurrence of the key     while curr is not None:         if curr.data == key:             lastPrev = prev             last = curr         prev = curr         curr = curr.next      # If the key was found     if last is not None:          # If last occurrence is not the head         if lastPrev is not None:             lastPrev.next = last.next         else:              # If last occurrence is the head,             # move head to next node             head = head.next      return head  def printList(curr):     while curr is not None:         print(curr.data, end=" ")         curr = curr.next     print()  if __name__ == "__main__":        # Create a hard-coded linked list:     # 1 -> 2 -> 2 -> 4 -> 2     head = Node(1)     head.next = Node(2)     head.next.next = Node(2)     head.next.next.next = Node(4)     head.next.next.next.next = Node(2)      key = 2     head = deleteLastOccurrence(head, key)      printList(head) 
C#
// C# program to delete last occurrence  // of key in singly linked list  class Node {     public int data;     public Node next;      public Node(int new_data) {         data = new_data;         next = null;     } }  class GfG {        // Function to delete the last occurrence      // of a key in the linked list     static Node deleteLastOccurrence(Node head, int key) {         Node last = null, lastPrev = null;         Node curr = head, prev = null;          // Traverse the list to find the last          // occurrence of the key         while (curr != null) {             if (curr.data == key) {                 lastPrev = prev;                 last = curr;             }             prev = curr;             curr = curr.next;         }          // If the key was found         if (last != null) {              // If last occurrence is not the head             if (lastPrev != null) {                 lastPrev.next = last.next;             } else {                  // If last occurrence is the head,                  // move head to next node                 head = head.next;             }         }          return head;     }      static void print(Node curr) {         while (curr != null) {             System.Console.Write(curr.data + " ");             curr = curr.next;         }         System.Console.WriteLine();     }      static void Main(string[] args) {                    // Create a hard-coded linked list:         // 1 -> 2 -> 2 -> 4 -> 2         Node head = new Node(1);         head.next = new Node(2);         head.next.next = new Node(2);         head.next.next.next = new Node(4);         head.next.next.next.next = new Node(2);          int key = 2;         head = deleteLastOccurrence(head, key);         print(head);     }    } 
JavaScript
// Javascript program to delete last occurrence  // of key in singly linked list  class Node {     constructor(new_data) {         this.data = new_data;         this.next = null;     } }  // Function to delete the last occurrence // of a key in the linked list function deleteLastOccurrence(head, key) {     let last = null, lastPrev = null;     let curr = head, prev = null;      // Traverse the list to find the last     // occurrence of the key     while (curr !== null) {         if (curr.data === key) {             lastPrev = prev;             last = curr;         }         prev = curr;         curr = curr.next;     }      // If the key was found     if (last !== null) {          // If last occurrence is not the head         if (lastPrev !== null) {             lastPrev.next = last.next;         } else {              // If last occurrence is the head,             // move head to next node             head = head.next;         }     }      return head; }  function printList(curr) {     while (curr !== null) {        console.log(curr.data + " ");         curr = curr.next;     } }  // Create a hard-coded linked list: // 1 -> 2 -> 2 -> 4 -> 2 let head = new Node(1); head.next = new Node(2); head.next.next = new Node(2); head.next.next.next = new Node(4); head.next.next.next.next = new Node(2);  let key = 2; head = deleteLastOccurrence(head, key); printList(head); 

Output
1 2 2 4  

Time Complexity: O(n), Traversing over the linked list of size n. 
Auxiliary Space: O(1)


Next Article
Delete last occurrence of an item from linked list

K

kartik
Improve
Article Tags :
  • Linked List
  • DSA
Practice Tags :
  • Linked List

Similar Reads

    Delete first occurrence of given Key from a Linked List
    Given a linked list and a key to be deleted. The task is to delete the first occurrence of the given key from the linked list. Note: The list may have duplicates. Examples: Input: list = 1->2->3->5->2->10, key = 2Output: 1->3->5->2->10Explanation: There are two instances o
    10 min read
    Delete all occurrences of a given key in a linked list
    Given a singly linked list, the task is to delete all occurrences of a given key in it.Examples:Input: head: 2 -> 2 -> 1 -> 8 -> 2 -> NULL, key = 2Output: 1 -> 8 -> NULL Explanation: All occurrences of the given key = 2, is deleted from the Linked ListInput: head: 1 -> 1 -
    8 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
    Modify a Linked List to contain last occurrences of every duplicate element
    Given an unsorted Singly Linked List consisting of N nodes that may contain duplicate elements, the task is to remove all but the last occurrence of duplicate elements from the Linked List. Examples: Input: 1 -> 2 -> 7 -> 3 -> 2 -> 5 -> 1Output: 7 -> 3 -> 2 -> 5 -> 1Exp
    10 min read
    Remove all occurrences of duplicates from a sorted Linked List
    Given a sorted linked list, delete all nodes that have duplicate numbers (all occurrences), leaving only numbers that appear once in the original list. Examples: Input : 23->28->28->35->49->49->53->53 Output : 23->35 Input : 11->11->11->11->75->75 Output : empt
    10 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