Stack With a Size Limit
Implement a class LimitedStack, a stack of integers with room for at most limit items. Write these methods:
LimitedStack(limit)makes an empty stack.push(x)putsxon top of the stack and returnstrue. If the stack already holdslimititems, the push is refused: the stack does not change and it returnsfalse.pop()removes the top item and returns it, or returns-1if the stack is empty.peek()returns the top item without removing it, or-1if the stack is empty.is_full()returnstrueif the stack holdslimititems andfalseotherwise.
The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.
Example 1
LimitedStack(2)
push(4) returns true
push(7) returns true
push(9) returns false
is_full() returns true
pop() returns 7
peek() returns 4
is_full() returns false
pop() returns 4
pop() returns -1
With room for two items, pushing 9 onto 4 7 is refused. Popping gives 7, then 4, and the empty stack pops -1.
Constraints
1 <= limit <= 50 <= x <= 100- Each test makes
1to40method calls after the constructor.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Classes problems
- Take a NumberBeginner
- Tally CounterBeginner
- Thermostat Between Two LimitsBeginner
- Whose Turn Is ItBeginner
- Average of the Last K ReadingsEasy
- Call Limiter per UserEasy
- Clinic Waiting RoomEasy
- Coffee Stamp CardsEasy