劍指offer第七天之用兩個棧實現隊列
用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素爲int類型。
棧A用來作入隊列
棧B用來出隊列,當棧B爲空時,棧A全部出棧到棧B,棧B再出棧(即出隊列)
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)
{
stack2.push(stack1.pop());
}
}
else if(stack2.size()==0)
{
return -1;
}
return stack2.pop();
}
}
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 len(self.stack2)<=0:
while len(self.stack1)!=0:
self.stack2.append(self.stack1.pop())
elif len(self.stack2)==0:
return None
return self.stack2.pop()