Skip to content

203. Remove Linked List Elements

203. Remove Linked List Elements

Companies: Amazon, Apple, Facebook, Google
Date: September 3, 2021 11:38 AM
Difficulty: Easy
Review Date: October 2, 2021
Status: Done
Tags: Linked List

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
        if not head:
            return None
        headbackup = current = head
        head = None

        foundFirstNonVal = False

        # print('current', current)
        while current:

            # set the head to the first node that does not have value = val
            if current.val == val:
                d = current
                current = current.next
                # print('in if')

            else:
                foundFirstNonVal = True
                head = current
                # print('in else')
                break

        if not foundFirstNonVal:
            return None

        # Now that we know the first one, let us proceed
        prev = head
        current = head

        while current and current.next:
            current = current.next
            if current.val == val:
                # delete the node
                prev.next = current.next

            else:
                prev = prev.next

        # print('\n\n')
        return head

Elegant recursion

def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
        """
        Time:
        Extra Space:
        """

        # base cases

                # when none
        # when val
        # when sth other than val

        if not head:
            return None
        if head.val == val:
            return self.removeElements(head.next, val)

                # recurrent relation
        head.next = self.removeElements(head.next, val)

        return head

Last update : 25 mai 2024
Created : 25 mai 2024