Implement Stack Using Queues
Build a last-in, first-out stack out of a first-in, first-out queue.
The problem
Implement the class MyStack, a last-in, first-out stack, using only queue operations: add to the back, remove from the front, look at the front, and check the size. You may use collections.deque, but only as a queue: append to the back and popleft from the front, never pop from the back. - MyStack() creates an empty stack. - push(value) puts value on top of the stack. - pop() removes the top value and returns it. - top() returns the top value without removing it. - empty() returns True if the stack has no values, otherwise False. For example, after push(1) and push(2), top() returns 2, pop() returns 2, and empty() returns False. Constraints: values are from 1 to 9, there are at most 100 calls, and pop and top are only called when the stack is not empty.
Starter code
class MyStack:
def __init__(self):
passPublic examples
obj = MyStack() obj.push(1) obj.push(2) obj.top() obj.pop() obj.empty()gives[None, None, None, 2, 2, False]obj = MyStack() obj.push(3) obj.pop() obj.empty()gives[None, None, 3, True]obj = MyStack() obj.push(4) obj.push(7) obj.top() obj.top()gives[None, None, None, 7, 7]
Solving it in the practice book needs an active paid plan.
Open it in the practice book