data-structures-algorithms-python icon indicating copy to clipboard operation
data-structures-algorithms-python copied to clipboard

remove_by_value implementation in singly_linked_list_exercise.py

Open satadrubasu opened this issue 3 years ago • 1 comments

https://github.com/codebasics/data-structures-algorithms-python/blob/master/data_structures/3_LinkedList/Solution/singly_linked_list_exercise.py

Proposed below :

        if not self.head:
            return

        if self.head.val == value:
            self.head = self.head.next
            return

        itr = self.head
        prev_node = None
        while itr:
            if itr.val == value:
                prev_node.next = itr.next
            prev_node = itr
            itr = itr.next

satadrubasu avatar May 11 '22 05:05 satadrubasu

You can simplify all the logic with just one while loop:

def remove_by_value(self, value_to_remove: Any) -> None:
        itr = self.head
        while itr:
            if value_to_remove == itr.next_value.data:
                itr.next_value = itr.next_value.next_value
                return
            itr = itr.next_value

        raise ValueError(f"{value_to_remove = } not found in the linked list")

gurashish1singh avatar Nov 05 '22 00:11 gurashish1singh