题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1 = [] #用来入队
self.stack2 = [] #用来出队
#将内容先push进一个栈stack1,
#判断stack2是否为空,空:将栈stack1中的元素pop(删除并返回数组的最后一个元素)
#并push进stack2,非空:直接出栈
#出栈时,先push进stack1先从stack2出来,即:实现了先进先出
def push(self, node):
# write code here
self.stack1.append(node) #入队
def pop(self):
# return xx
if self.stack2: #如果stack2有元素,直接出队
return self.stack2.pop()
while self.stack1: #当stack2没有元素时,将stack1的元素逆序存入到stack2中
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
class Solution
{
public:
void push(int node)
{
stack1.push(node);
}
int pop()
{
int tmp;
if (stack2.empty())
{
while (!stack1.empty())
{
tmp = stack1.top();
stack2.push(tmp);
stack1.pop();
}
}
tmp = stack2.top();
stack2.pop();
return tmp;
}
private:
stack<int> stack1;
stack<int> stack2;
};
int main()
{
Solution *s = new Solution();
for (int i = 0; i<10; i++)
{
s->push(i);
if (i == 5)
{
s->pop();
cout << s->pop() << endl;
}
}
system("pause");
return 0;
}