342. Delete Last Occurrence of a Given Value

EasyLinked ListLinked ListDeletionTraversal

Given the head of a singly linked list and an integer val, delete the last occurrence of a node with value val. Return the head.

If val is not found, return the list unchanged.

Input: Head of a singly linked list and integer val.

Output: Head of the updated linked list.

Examples

Example 1
Input: [1,2,3,2,4,2,5], 2
Output: [1,2,3,2,4,5]
Explanation: Last occurrence of 2 is at position 6. Delete it.
Example 2
Input: [1,2,3], 1
Output: [2,3]
Explanation: Only occurrence of 1 is the head. Delete head.
Example 3
Input: [1,2,3], 4
Output: [1,2,3]
Explanation: 4 not found. Return unchanged.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →