Add at the front: O(1)
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def show(head):
out = []
while head:
out.append(str(head.value))
head = head.next
print(" -> ".join(out) or "(empty)")
head = Node(2, Node(3))
head = Node(1, head) # new node points at the old head
show(head)Output
1 -> 2 -> 3
Add at the end: O(n)
You have to walk to the last node first (unless you also keep a tail pointer):
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def append(head, value):
if head is None:
return Node(value)
current = head
while current.next:
current = current.next
current.next = Node(value)
return head
head = None
for v in [5, 6, 7]:
head = append(head, v)
node = head
while node:
print(node.value, end=" ")
node = node.next
print()Output
5 6 7
Remove a value
To remove a node, make the node before it skip over it. A dummy node in front makes removing the head work the same way as removing any other node:
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def remove_all(head, target):
dummy = Node(0, head)
prev = dummy
while prev.next:
if prev.next.value == target:
prev.next = prev.next.next # skip it
else:
prev = prev.next
return dummy.next
head = Node(7, Node(1, Node(7, Node(2, Node(7)))))
head = remove_all(head, 7)
while head:
print(head.value)
head = head.nextOutput
1 2
Think of it like this: Removing someone from a human chain: the person before them lets go and grabs the hand of the person after them.
Common mistake: Always check for
Nonebefore using.next.None.nextcrashes with anAttributeError.