Theory

Pencil trace: what the pointers do in a move

There is no code here. Before you read playlist.go, watch what a linked list does with its pointers — on a five-track playlist. Short names are letters:

A = Aidas   B = Bangos   C = Ciklas   D = Dūmai   E = Ežeras

How we count

Two counters, exactly the ones you will see in Splice's signature:

  • walk — one hop from a node to its neighbour, until you reach the node you need;
  • ptr writes — the four neighbour pointers a move rewrites. The moved node's own two pointers are also set, but the counter does not count them — this is the same "four" step 1 talked about.

The list

Five Append calls. Each reaches the end through Tail — no walk at all:

Head                                          Tail
 │                                              │
 ▼                                              ▼
[A] ⇄ [B] ⇄ [C] ⇄ [D] ⇄ [E]

Each ⇄ is two pointers: Next to the right and Prev to the left.

Moving D to position 1

The user drags Dūmai (position 3) to position 1 — in front of Bangos.

1. First you have to walk to both nodes. From Head, one hop at a time:

NodeAt(3):   A → B → C → D        3 hops
NodeAt(1):   A → B                1 hop
                            walk: 4

2. unlink(D) — cut D out of its old place. Two neighbour pointers:

before:   [C] ⇄ [D] ⇄ [E]
                C.Next = E          pointer 1
                E.Prev = C          pointer 2
after:    [C] ⇄ [E]        [D]      D is detached

3. insertBefore(D, B) — stitch it in ahead of B. Two more neighbour pointers (and D's own two):

before:   [A] ⇄ [B]                 [D]
                A.Next = D          pointer 3
                B.Prev = D          pointer 4
                D.Prev = A, D.Next = B
after:    [A] ⇄ [D] ⇄ [B]

The whole list after the move:

[A] ⇄ [D] ⇄ [B] ⇄ [C] ⇄ [E]        walk 4, pointer writes 4

Two counters, two different numbers: 4 hops to reach the nodes, and 4 pointer writes to move. The numbers come from running the Playlist code on this five-item playlist.

Three observations.

1. The move itself is four pointers, wherever. Four in this list and four in a list of a million. No element except the neighbours around D was touched or "pushed" anywhere.

2. Reaching the node is a separate cost. D was third from the front, so 3 hops; B was 1 hop. If D were last in a list of a million, that would be a million hops — and still four pointer writes. That is why Splice takes two counters, not one.

3. Nodes do not move in memory. Only who-points-at-whom changed. What an array does by pushing elements along is simply not done here — and it is precisely that trade (a walk instead of a push) that decides who wins. You measure the comparison with []Item in step 5.

What comes next

In the next step you read the code that does this: Node, Playlist, NodeAt, unlink, insertBefore and the two counters.