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)