P5-7 由两个栈组成的队列
书中思路 Python实现
class TwoStacksQueue(object): def __init__(self): self.stackPush = [] self.stackPop = [] def pushToPop(self): if not self.stackPop: while self.stackPush: self.stackPop.append(self.stackPush.pop()) def add(self, pushInt): self.stackPush.append(pushInt) self.pushToPop() def poll(self): try: self.pushToPop() except Exception: print("栈为空") return self.stackPop.pop() def peek(self): try: self.pushToPop() except Exception: print("栈为空") return self.stackPop[-1] n = int(input()) s = TwoStacksQueue() for _ in range(n): command = input().split() if command[0] == 'add': s.add(command[1]) elif command[0] == 'poll': s.poll() elif command[0] == 'peek': print(s.peek())
排行榜优解
import sys n = int(sys.stdin.readline()) stackPush = [] for _ in range(n): command = sys.stdin.readline().strip().split() if command[0]=='add': stackPush.append(command[1]) elif command[0]=='peek': print(stackPush[0]) elif command[0]=='poll': stackPush = stackPush[1:]
虽然OJ能过,但明显这种解法已经背离的题意了,只使用了一个列表来实现,对比书中的思路可以发现,书中对于此题的目的是利用两次栈的先进后出的特性来达到队列先进先出的目的.