diff --git a/questions/add_remove_ll/add_remove_linked_list.md b/questions/add_remove_ll/add_remove_linked_list.md index 8a5fbce..6a8323b 100644 --- a/questions/add_remove_ll/add_remove_linked_list.md +++ b/questions/add_remove_ll/add_remove_linked_list.md @@ -4,4 +4,5 @@ Create the methods that adds and remove data to a linked list ###Solutions - [Jessica's Solution - Python2.7](https://github.com/chatasweetie/whiteboarding-and-coding-problems/blob/master/questions/add_remove_ll/solution/add_remove_linked_list.py) +- [Arcy's Solution - Python 3.12](./solution/add_remove_ll_arcy.py) diff --git a/questions/add_remove_ll/solution/add_remove_ll_arcy.py b/questions/add_remove_ll/solution/add_remove_ll_arcy.py new file mode 100644 index 0000000..6b6038c --- /dev/null +++ b/questions/add_remove_ll/solution/add_remove_ll_arcy.py @@ -0,0 +1,61 @@ +class Node: + def __init__(self, value=None, next=None): + self.value = value + self.next = next + + def __repr__(self): + return f"Node({self.value})" + +class LinkedList: + def __init__(self): + self.head = None + + def add(self, value): + new_node = Node(value) + if self.head is None: + self.head = new_node + else: + current_node = self.head + while current_node.next: + current_node = current_node.next + current_node.next = new_node + + def prepend(self, value): + new_node = Node(value) + new_node.next = self.head + self.head = new_node + + def remove(self, value): + if self.head is None: + return # List is empty, nothing to delete + + if self.head.value == value: + self.head = self.head.next + return + + current_node = self.head + while current_node.next and current_node.next.value != value: + current_node = current_node.next + + if current_node.next: # We found the value + current_node.next = current_node.next.next + + def __repr__(self): + current_node = self.head + nodes = [] + while current_node: + nodes.append(str(current_node.value)) + current_node = current_node.next + return " -> ".join(nodes) + " -> None" + +ll = LinkedList() +ll.add(1) +ll.add(2) +ll.add(3) +print(ll) # Output: 1 -> 2 -> 3 -> None + +ll.prepend(0) +print(ll) # Output: 0 -> 1 -> 2 -> 3 -> None + +ll.remove(2) +print(ll) # Output: 0 -> 1 -> 3 -> None