用两个栈实现队列 -- Java和python实现
python实现
# -*- coding:utf-8 -*- class Solution: def __init__(self): self.stack1 = [] self.stack2 = [] def push(self, node): # write code here self.stack1.append(node) def pop(self): # return xx if self.stack2 == []: while self.stack1 != []: self.stack2.append(self.stack1.pop()) if self.stack2 != []: return self.stack2.pop() else: return None
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.push(node); } public int pop() { if(stack2.size()<=0){ while(stack1.size()>0){ int temp = stack1.pop(); stack2.push(temp); } } return stack2.pop(); } }