剑指offer 5、用两个栈实现队列 python和c++
题目:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:先用一个栈1来存 “进队列” 的数据,另一个栈2把栈1数据元素反转来作为 “出队列” 的顺序,此时把栈1清空。在栈2的数据没出队列完的时候,栈1累计后面进队列的数据。到栈2的数据都出队列了,又把栈1数据元素反转放到栈2来作为 “出队列” 的顺序,此时又把栈1清空。
其实也挺好理解,栈2存的都是某次出队列前进队列的数据,在栈2没空之前,栈2里面的数据都是最先进队列的,肯定要先出。
c++版
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.size() == 0){ //栈2为空的时候把 栈1的数据反转放在栈2里面
while(stack1.size()){
stack2.push(stack1.top());
stack1.pop();
}
}
int res = stack2.top();
stack2.pop();
return res;
}
private:
stack<int> stack1;
stack<int> stack2;
};
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())
return self.Stack2.pop()
return self.Stack2.pop()