Delete last occurrence of an item from linked list
Last Updated :
20 Sep, 2024
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
Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> NULL , key = 3
Output: 1 -> 2 -> 4 -> 5 -> NULL
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);
Time Complexity: O(n), Traversing over the linked list of size n.
Auxiliary Space: O(1)
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
Delete alternate nodes of a Linked List Given a Singly Linked List, starting from the second node delete all alternate nodes of it. For example, if the given linked list is 1->2->3->4->5 then your function should convert it to 1->3->5, and if the given linked list is 1->2->3->4 then convert it to 1->3. Recomm
14 min read