题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路
通过两个栈来进行,push的时候用第一个栈就好了,pop的时候,用第二个栈把第一栈中的元素都push进去。当要pop的时候就pop第二个栈的元素,当第二个栈为空的时候再把第一个栈的元素push进第二个栈的元素。
做题可能出现的问题
1、 注意判断条件
2、注意c++中top和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 not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
res = self.stack2.pop()
return res
C++
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if (stack2.empty())
{
while(!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
}
int res = stack2.top();
stack2.pop();
return res;
}
private:
stack<int> stack1;
stack<int> stack2;
};
网友评论