栈 先进后出(FILO)
队列 先进先出(FIFO)
class MyQueue: # 两栈模拟队列 def __init__(self): self.input = [] self.output = [] #进队列 def push(self, x): self.input.append(x) #出队列 def pop(self): self.peek() return self.output.pop()
def peek(self): if not self.output: #output为空时,将input中的数倒入output while self.input: self.output.append(self.input.pop()) return self.output[-1] #返回队列顶端的数 def is_empty(self): return not self.output and not self.input obj = MyQueue() obj.push(1) obj.push(2) obj.push(3) # peek = obj.peek() num = obj.pop() print(num)
class MyStack: # 用两个队列模拟栈 def __init__(self): self.s1 = [] self.s2 = [] self.num = 0 # 标志队列元素 def push(self, x): self.s1.append(x) self.num = x def pop(self): if self.s2: for _ in range(len(self.s2)-1): self.num = self.s2.pop(0) self.s1.append(self.num) return self.s2.pop() else: for _ in range(len(self.s1)-1): self.num = self.s1.pop(0) self.s2.append(self.num) return self.s1.pop() def top(self): return self.num def is_empty(self): return not self.s1 and not self.s2