用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
=================Python===============
# -*- coding:utf-8 -*- class Solution: def __init__(self): self.s1 = [] self.s2 = [] def push(self, node): # write code here self.s1.append(node) def pop(self): # return xx if len(self.s2) == 0: while self.s1: self.s2.append(self.s1.pop()) return self.s2.pop()
====================Java=================
import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.add(node); } public int pop() throws Exception { if (stack2.isEmpty()) { while (!stack1.isEmpty()) { stack2.add(stack1.pop()); } } if (stack2.isEmpty()) throw new Exception("error"); return stack2.pop(); } }