VOOZH about

URL: https://www.geeksforgeeks.org/dsa/delete-last-occurrence-of-an-item-from-linked-list/

⇱ Delete last occurrence of an item from linked list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

👁 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.

Output
1 2 2 4 

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

Comment
Article Tags:
Article Tags: