题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
解题思路
1、完成队列的插入操作,直接在栈1中插入即可(stack1.push(data))
2、当需要删除(pop)时,stack2不为空时,直接弹出栈顶的元素,注意stack.top()记录元素进行返回。如果stack2为空,则将stack1中的所有元素压入stack2中,然后弹出即可。
C++实现
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.size() <= 0)
{
while(stack1.size() > 0)
{
int a = stack1.top();
stack1.pop();
stack2.push(a);
}
}
int result = stack2.top();
stack2.pop();
return result;
}
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.stack2.append(node)
def pop(self):
# return xx
if self.stack1:
return self.stack1.pop()
elif self.stack2 is None:
return None
else:
while self.stack2:
self.stack1.append(self.stack2.pop())
return self.stack1.pop()