Push as insert at head
Updated
List-stack push is insert-at-head: new.next = oldHead; head = new. That is O(1) and makes the new value the top. The old chain is the rest.
What to focus on
Insert at tail would make push O(n) and reverse the LIFO unless you also pop from tail. That is a deque, not this stack.
Worked examples
onto three
a = [4, 1, 9] as 9→1→4, push 8- 8.next ← 9
- head 8
Result: 8 → 9 → 1 → 4
onto empty
a = [], push 4- head ← 4
- 4.next null
Result: 4 → null
tail insert bug
a = [4, 1, 9], append 8 at tail- 8 is bottom
- top still 9
Result: wrong stack
Try it
Write pushHead(head, x). head is the top node, or null if empty. x is the integer to push. node.next is the next node toward the bottom. Insert at head. Appending at the tail puts x on the bottom and breaks LIFO. Push 8 onto list-backed [4, 1, 9] → 8 → 9 → 1 → 4. Push 4 onto empty → 4 → null.
Head is the top. Values are integers. You may push onto empty.