Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions questions/add_remove_ll/add_remove_linked_list.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

61 changes: 61 additions & 0 deletions questions/add_remove_ll/solution/add_remove_ll_arcy.py
Original file line number Diff line number Diff line change
@@ -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