A linked list is a node with a value and a pointer to the next node. Finding the k-th item is Θ(n). Inserting after a node you already hold is Θ(1).
Goal
Build a short list of cities, walk it, and insert after the head.
Walk
class Node:
def __init__(self, value, nxt=None):
self.value = value
self.next = nxt
def to_list(head):
out = []
steps = 0
cur = head
while cur:
steps += 1
out.append(cur.value)
cur = cur.next
return out, steps
head = Node("Nairobi", Node("Mombasa", Node("Kisumu")))
print(to_list(head))Three nodes, three steps. No random access.
Insert after a node
class Node:
def __init__(self, value, nxt=None):
self.value = value
self.next = nxt
def insert_after(node, value):
node.next = Node(value, node.next)
head = Node("Nairobi", Node("Kisumu"))
insert_after(head, "Mombasa")
cur = head
while cur:
print(cur.value)
cur = cur.nextOne pointer assignment. You did not shift Kisumu in an array — you retargeted next.
Find, then insert
class Node:
def __init__(self, value, nxt=None):
self.value = value
self.next = nxt
def find(head, target):
steps = 0
cur = head
while cur:
steps += 1
if cur.value == target:
return cur, steps
cur = cur.next
return None, steps
head = Node("Nairobi", Node("Mombasa", Node("Kisumu")))
node, steps = find(head, "Mombasa")
print("steps to find", steps, "value", node.value)The insert is cheap after the find. The find is linear.
Pitfall
There is no head[2]. If the recipe needs the middle often, use an array (Python list), not a linked list.