Data Structures19 sections · 729 units
Open in Course

DLL Insertion

Update both directions

To insert a new node after a given node prev:

newNode = new DListNode(val)
newNode.next = prev.next
newNode.prev = prev
if prev.next != null:
    prev.next.prev = newNode
prev.next = newNode

Four pointer updates instead of two. The order matters. Updating prev.next last ensures you don't lose the reference to the node that follows.

For LRU caches, you often use sentinel nodes: a dummy head and dummy tail that always exist. This eliminates null checks:

head.next = tail
tail.prev = head

Every real node sits between these sentinels.