|
| 1 | +# Remove Linked List Elements |
| 2 | + |
| 3 | +Difficulty: easy |
| 4 | +Done: Yes |
| 5 | +Last edited: February 27, 2022 1:25 AM |
| 6 | +Link: https://leetcode.com/problems/remove-linked-list-elements/ |
| 7 | +Topic: linked list |
| 8 | + |
| 9 | +## Problem |
| 10 | + |
| 11 | +Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return *the new head*. |
| 12 | + |
| 13 | +``` |
| 14 | +Input: head = [1,2,6,3,4,5,6], val = 6 |
| 15 | +Output: [1,2,3,4,5] |
| 16 | +``` |
| 17 | + |
| 18 | +## Solution |
| 19 | + |
| 20 | +Similar to linked list reversal using two pointer iterative approach. Whenever the current node in traversals value is equivalent to our target, we point the `previous` node to the `current.next` node. Else, we will continue our traversal. Hereby shifting the previous pointer and current pointer iteratively. |
| 21 | + |
| 22 | +There’s a caveat, however, whenever the first node of our list is our target —or repeated. Because previous remains undefined. Therefore we need to check if previous is defined beforehand. |
| 23 | + |
| 24 | +## Whiteboard |
| 25 | + |
| 26 | + |
| 27 | + |
| 28 | +With target value equal to 6 |
| 29 | + |
| 30 | + |
| 31 | + |
| 32 | +Problem becomes trickier when target exist as first (or consecutively) node(s) |
| 33 | + |
| 34 | +## Code |
| 35 | + |
| 36 | +```python |
| 37 | +# Definition for singly-linked list. |
| 38 | +# class ListNode: |
| 39 | +# def __init__(self, val=0, next=None): |
| 40 | +# self.val = val |
| 41 | +# self.next = next |
| 42 | +class Solution: |
| 43 | + def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: |
| 44 | + |
| 45 | + # for empty list |
| 46 | + if head is None: |
| 47 | + return None |
| 48 | + |
| 49 | + current = head |
| 50 | + previous = None |
| 51 | + |
| 52 | + while current is not None: |
| 53 | + |
| 54 | + if current.val == val: |
| 55 | + |
| 56 | + if previous is None: |
| 57 | + # this will happen when target exist at first node |
| 58 | + # or consectuive first (n) nodes |
| 59 | + head = head.next |
| 60 | + current = head |
| 61 | + |
| 62 | + if previous: |
| 63 | + previous.next = current.next |
| 64 | + current.next = None |
| 65 | + current = previous.next |
| 66 | + |
| 67 | + # else keep traversing |
| 68 | + else: |
| 69 | + previous = current |
| 70 | + current = current.next |
| 71 | + |
| 72 | + |
| 73 | + return head |
| 74 | +``` |
0 commit comments