题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
用一个栈作为接受输入值,另外一个栈作为输出,但要注意的是要判断输出的栈为空。
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() {
while(!stack2.isEmpty()){
return stack2.pop();
}
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
python代码:
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stackin=[]
self.stackout=[]
def push(self, node):
# write code here
self.stackin.append(node)
def pop(self):
# return xx
if self.stackout==[]:
while self.stackin:
self.stackout.append(self.stackin.pop())
return self.stackout.pop()
else:
return self.stackout.pop()