栈:LIFO
队列:FIFO
及入队的假如是1,2,3 则出队也是1,2,3
C++实现:
class Solution
{
public:
void push(int node) {//入队时需要保证stack2为空
while(!stack2.empty()){//如果stack2中有元素,先压入栈stack1,并清空stack2
stack1.push(stack2.top());
stack2.pop();
}
stack1.push(node);
}
int pop() {//出队需要返回int型数据
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
int temp = stack2.top();
stack2.pop();
return temp;
}
private:
stack<int> stack1;
stack<int> stack2;
};
C++完整代码:
#include<iostream>
#include<stack>
using namespace std;
class Solution
{
public:
void push(int node) {
while (!stack2.empty())//入队时,要保证stack2为空,如果stack2为空,则stack2.empty()返回True,
{
stack1.push(stack2.top());
stack2.pop();
}
stack1.push(node);//将int型的元素node压入栈1
cout << "入队元素是:" << stack1.top() << endl;
}
int pop() {
while (!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
cout << "出队元素是:" << stack2.top() << endl;
int temp = stack2.top();
stack2.pop();
return temp;
}
private:
stack<int> stack1;//作为入队序列
stack<int> stack2;//作为出队序列
};
int main()
{
Solution so;
so.push(1);
so.push(2);
so.push(3);
so.pop();
so.pop();
so.pop();
//so.push(4);
//so.pop();
//so.push(5);
//so.pop();
//so.pop();
cout << endl;
return 0;
}
python2.7.3实现:
# -*- coding:utf-8 -*-
class Solution:
#定义两个空栈
stack1 = []
stack2 = []
def push(self, node):#实现入队
# write code here
while len(self.stack2)>0:#如果stack2非空,先将其中的元素压入stack1,使其空
self.stack1.append(self.stack2.pop())
self.stack1.append(node)#python中在类里面调用属性或方法,前面要加self
def pop(self):#实现出队
# return xx
if self.stack2==[]:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
while self.stack2:
self.stack1.append(self.stack2.pop())
python中的列表自带pop()函数,用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。