Stacks and Queues Building stacks and queues
188. Implement a Stack with a Linked List
Build a stack of integers on a singly linked list. Write a class LinkedStack with a constructor and four
methods:
LinkedStack()creates an empty stack.push(val)putsvalon top of the stack.pop()removes the value on top and returns it. If the stack is empty, it returns-1and changes nothing.top()returns the value on top without removing it, or-1if the stack is empty.size()returns how many values the stack holds.
Keep each value in a node of your own: an object that holds the value and a link to the next node. Do not use a built-in stack, an array, or a list from the language's library. The stack has no capacity, so every push is kept. Each method must run in O(1) time.
Your class is tested by replaying a list of calls on a new LinkedStack(). ops[i] names the i-th call:
"push", "pop", "top" or "size". The pushes take their values from values in order, so the first
push pushes values[0], the second pushes values[1], and so on. The answer is the list of every value
that pop, top and size return, in the order they are called.
In C# and Go the methods are Push, Pop, Top and Size. Go creates the stack with Constructor(), and
Rust with LinkedStack::new(). The names in ops are the same in every language.
Example 1
Input: ops = ["push",
"push",
"push",
"top",
"pop",
"push",
"size",
"pop",
"pop"]
values = [5, 12, 40, 7]
[40,40,3,7,12]Explanation: After the first three pushes the stack holds 5, 12 and 40 from the bottom up. top and pop both give
40, the newest value. Then 7 goes on top of 12, size counts 5, 12 and 7, and the pops return 7 and 12.
Example 2
Input: ops = ["pop",
"size",
"push",
"top",
"pop",
"top",
"size"]
values = [0]
[-1,0,0,0,-1,0]Explanation: pop on the empty stack returns -1, and size stays 0. The pushed 0 is a real value, so top and pop
return it. The stack is then empty again, and top returns -1.
Example 3
Input: ops = ["push",
"push",
"push",
"push",
"push",
"push",
"size",
"pop",
"top"]
values = [1000000000, 3, 3, 3, 0, 999999999]
[6,999999999,0]Explanation: The stack has no capacity, so it keeps all six values, and the three 3s are three separate values. pop
removes 999999999, which leaves 0 on top.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ ops.length ≤ 105- Each
ops[i]is"push","pop","top"or"size". values.lengthequals the number of"push"calls inops.0 ≤ values[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.