AlgoFrames

Implement a stack with a linked list

Challenge · Write code · about 20 min

Complete LinkedStack using Node objects (a value and a next pointer) and a top pointer. Do not use an array to hold the values, and keep every operation O(1).

  • push(x) adds x on top.
  • pop() removes and returns the top value, or -1 when the stack is empty.
  • peek() returns the top value, or -1 when empty.
  • size() returns the number of values.

The given runLinkedStack(ops) collects the results of pop, peek and size.

Example 1

Input:

[["push 3","push 8","peek","pop","size","pop","pop"]]

Output:

[8,8,1,3,-1]

After the second pop the stack is empty, so the third pop returns -1.

Example 2

Input:

[["push 1","push 2","push 3","size","pop","peek"]]

Output:

[3,3,2]

Constraints

  • 1 ≤ ops.length ≤ 1, 000
  • Each op is "push x" with 0 ≤ x ≤ 1, 000, "pop", "peek" or "size"

Learn the idea first: Stacks: push, pop, peek; array and linked implementations, a visual lesson.

More Stacks: push, pop, peek; array and linked implementations problems