awelgorithms

Treat head as the top

Updated

Peek is head.value. Size is a stored count or a walk. Mixing tail is top with head is top in one implementation is how LIFO flips by accident.

What to focus on

If head is top, every public operation uses head. Draw it. Tests: push then peek equals the pushed value immediately.

Worked examples

peek head

a = [4, 1, 9] as 9→1→4
  1. head.value 9

Result: top 9

after push

a = [4, 1, 9], push 8 at head
  1. head.value 8

Result: top 8

after pop

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

Result: top 1

Try it

Write peekHead(head). head is the top node. node.next is the next node toward the bottom. Peek via head.value. Never peek the tail. On list-backed [4, 1, 9] peek is 9. After push 8 peek is 8. After pop peek is 1.

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