awelgorithms

Pop as delete the head

Updated

List-stack pop is delete-head: x = head.value; head = head.next; return x. The new head is the new top.

What to focus on

You do not find the tail. You do not rewire the bottom. One pointer move.

Worked examples

three

a = [4, 1, 9] as 9→1→4, pop
  1. x=9
  2. head=1

Result: popped 9, 1 → 4

one

a = [7] as 7→null, pop
  1. head becomes null

Result: popped 7, empty

two

a = [4, 1] as 1→4, pop
  1. x=1
  2. head=4

Result: popped 1, 4 → null

Try it

Write popHead(head). head is the top node. node.next is the next node toward the bottom, or null if this was the last item. Delete the head and return its value. The new head is the new top. Pop list-backed [4, 1, 9]: new head is 1. Pop [7]: head becomes null. Pop [4, 1]: new head is 4.

The list-backed stack is non-empty. Head is the top. Values are integers.