Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to remove last occurrence of a given target from a linked list in Python
Suppose we have a singly linked list and a target value, we have to remove the last occurrence of the target from the given list.
So, if the input is like [5,4,2,6,5,2,3,2,4,5,4,7], target = 5, then the output will be [5, 4, 2, 6, 5, 2, 3, 2, 4, 4, 7]
Algorithm
To solve this, we will follow these steps −
- Initialize head := node
- Set k := null, prev := null
- Set found := False
- While node is not null, do
- If value of node is same as target, then
- found := True
- prev := k
- k := node
- node := next of node
- If value of node is same as target, then
- If found is False, then
- return head
- If prev is null, then
- return next of head
- next of prev := next of the next of prev
- return head
Example
Let us see the following implementation to get better understanding −
class ListNode:
def __init__(self, data, next=None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
result = []
while ptr:
result.append(ptr.val)
ptr = ptr.next
print(result)
class Solution:
def solve(self, node, target):
head = node
k = None
prev = None
found = False
while node:
if node.val == target:
found = True
prev = k
k = node
node = node.next
if found == False:
return head
if not prev:
return head.next
prev.next = prev.next.next
return head
# Example usage
ob = Solution()
linked_list = make_list([5, 4, 2, 6, 5, 2, 3, 2, 4, 5, 4, 7])
target = 5
print("Original list:")
print_list(linked_list)
result = ob.solve(linked_list, target)
print("After removing last occurrence of", target, ":")
print_list(result)
Original list: [5, 4, 2, 6, 5, 2, 3, 2, 4, 5, 4, 7] After removing last occurrence of 5 : [5, 4, 2, 6, 5, 2, 3, 2, 4, 4, 7]
How It Works
The algorithm traverses the linked list once and keeps track of the previous node of each target occurrence. When the traversal completes, prev points to the node before the last occurrence of the target. We then remove the target node by updating the next pointer of prev.
Special cases handled:
- If target not found, return original list
- If last occurrence is the first node, return
head.next - Otherwise, skip the target node by updating
prev.next
Conclusion
This solution removes the last occurrence of a target value from a linked list in O(n) time complexity with a single pass traversal. The key insight is tracking the previous node of each target occurrence to enable efficient removal.
