Implement Stack using Linked List

easy

Implement a stack (last-in, first-out) backed by a singly linked list, supporting:

  • push(x) — add x to the top.
  • pop() — remove and return the top element; return -1 if the stack is empty.

Both operations must be O(1). The first operation names the class (its constructor).

Hints

Which end of a singly linked list supports O(1) insertion and removal?
Keep a head pointer as the top: push prepends, pop unlinks the head.
Return -1 when the head is null.

Common doubts

Head operations are O(1) with no traversal. Tail operations on a singly linked list require walking to the end (O(n)) unless you also track a tail pointer.
A linked list never resizes and uses exactly one node per element, at the cost of a pointer per node and an allocation per push.

Interview follow-ups

peek() returns head's value without advancing; size() is maintained with a counter incremented on push and decremented on pop.
Yes — free popped nodes to avoid leaks (managed languages garbage-collect them automatically).

Fun facts

  • A linked-list stack is the textbook example of why 'insert at head' is the linked list's superpower.
  • Persistent (immutable) stacks share tails between versions — pushing returns a new head pointing at the old list, leaving it intact.

Asked at

AmazonMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: push(5), push(10), pop(), pop(), pop()
Output: 10, 5, -1
LIFO: the last pushed (10) is popped first, then 5, then -1.
Example 2
Input: push(7), pop()
Output: 7
Push 7, pop returns 7.
Constraints

- 1 <= number of operations <= 100 - 1 <= x <= 10^5 - pop() returns -1 if the stack is empty.

Solve this problem →