Write a class, use two stacks to implement a queue, support the basic operation of the queue (add,poll,peek)
Idea: the stack is characterized by first in first out, and the queue is characterized by first in first out. The specific implementation is that one stack is used as the push in stack. When pressing data, only press it into this stack, which is recorded as stackPush. The other stack is only used as the pop-up stack. When popping data, only pop it out from this stack, which is recorded as stackPop.
Note that two points need to be met:
1. If stackPush wants to push data into stackPop, stackPop's stack must be empty.
2. When pressing data from stackPush to stackPop, all data of stackPush must be pressed in at one time.
class Stack(): def __init__(self): self.item = [] def pop(self): if len(self.item)==0: return "the Stack is empty" else: self.item.pop() def push(self,item): self.item.append(item) def peek(self): return self.item[len(self.item)-1] def isEmpty(self): if len(self.item)==0: return True return False class MyStack(): def __init__(self): self.stackPush = Stack() self.stackPop = Stack() def pushTopPop(): if self.stackPop.isEmpty: while self.stackPush.isEmpty is not True: self.stackPop.push(self.stackPush.pop()) def add(num): self.stackPush(num) self.pushToPop() def poll(): if self.stackPop.empty() and self.stackPush.empty(): return "queue is empty" self.pushToPop() return self.stackPop.pop() def peek(): if self.stackPop.empty() and self.stackPush.empty(): return "Queue is empty" self.pushToPop() return stackPop.peek()