24/39
Part 5 of 7 · Doubly linked listsLearn
A doubly linked list unlinks a node you hold in O(1)
Give each node a second pointer, prev, to the node before it, and a node can leave the list on its own. The price is one more pointer per node, and twice the assignments to keep right.
class DNode:
def __init__(self, key=None):
self.key = key
self.prev = self.next = None
# sentinels: they hold no key and never leave
head, tail = DNode(), DNode()
# the empty list
head.next, tail.prev = tail, head
def insert_after(node, new):
new.prev, new.next = node, node.next
node.next.prev = new
node.next = new
def unlink(node):
node.prev.next = node.next
node.next.prev = node.prev
def forward(limit=100):
out, node = [], head.next
while node is not tail and len(out) < limit:
out.append(node.key)
node = node.next
return out
def backward(limit=100):
out, node = [], tail.prev
while node is not head and len(out) < limit:
out.append(node.key)
node = node.prev
return out[::-1]
for key in "abc":
insert_after(tail.prev, DNode(key))
c = tail.prev
unlink(c)
insert_after(head, c)
print(forward(), backward())
Push a, b and c to the back, then move c to the front. What do forward() and backward() print?
Pick one to see what it prints.
Pick an answer above to see the rest