05-用两个栈来实现一个队列的push与pop操作

栈: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()函数,用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值