Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

remove_by_value implementation in singly_linked_list_exercise.py #54

Open
satadrubasu opened this issue May 11, 2022 · 1 comment
Open

Comments

@satadrubasu
Copy link

satadrubasu commented May 11, 2022

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
@gurashish1singh
Copy link

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")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants