【LeetCode】225. 用队列实现栈

2020.6.30号更新

思路

思路和以前一样,此次复习时,对精简了代码

代码

#include<iostream>
#include<queue>
using namespace std;
class MyStack {
public:
    queue<int> q1, q2;//q1进行插入和保存数据,q2作为辅助队列
    /** Initialize your data structure here. */
    MyStack() {

    }

    /** Push element x onto stack. */
    void push(int x) {
        q1.push(x);
    }

    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        if (q1.empty()) return -1; //判断q1是否为空
        while (q1.size()>1)//q1中还剩下1个元素时
        {
            q2.push(q1.front());
            q1.pop();
        }
        int value = q1.front();
        q1.pop();
        swap(q1, q2);//交换q1和q2
        return value;
    }

    /** Get the top element. */
    int top() {
        int value = pop();//先pop拿到要出来的元素值
        q1.push(value);//再将其压回
        return value;
    }

    /** Returns whether the stack is empty. */
    bool empty() {
        if (q1.empty()) return true;
        return false;
    }
};

解题思路

队列的特性:先进先出
栈的特性:先进后出
在解决用栈实现队列问题时,利用的是两个栈,采用的是利用辅助栈来实现队列的功能。因此对于此题也可以使用此思想。
利用两个队列,一个作为输入队列inputQ,一个作为输出队列outputQ。

  • 对于MyStack.push()操作,由inputQ完成
  • 对于MyStack.pop()操作,由于栈的先进后出特性,可以使inputQ不断的pop,并将其值压回到outputQ,直到inputQ.size()==1即为此时应该出栈的元素,记录下来。
  • 之后再把outputQ中的元素压回到inputQ中(可使用inputQ=outputQ完成该操作),outputQ清空,至此该过程结束。
  • 对于MyStack.top()操作,类似于pop,只不过把可以进行简化一下,对inputQ不断pop,并记录front,直达为空,同时将该值压回到outputQ。之后把outputQ赋值给inputQ即可。
    对于MyStack.empty()操作,判断inputQ是否为空即可。

代码

class MyStack {
public:
	/** Initialize your data structure here. */
	deque<int> inputQ;
	deque<int> outputQ;
	MyStack() {

	}

	/** Push element x onto stack. */
	void push(int x) {
		inputQ.push_back(x);
	}

	/** Removes the element on top of the stack and returns that element. */
	int pop() {
		int popNum=0;
		if (!inputQ.empty())
		{
			while (inputQ.size()!=1)
			{
				outputQ.push_back(inputQ.front());
				inputQ.pop_front();
			}
			popNum = inputQ.front();
			inputQ.pop_front();
			inputQ = outputQ;
			outputQ.clear();
		}
		return popNum;
	}

	/** Get the top element. */
	int top() {
		int popNum = 0;
		if (!inputQ.empty())
		{
			while (!inputQ.empty())
			{
				popNum = inputQ.front();
				outputQ.push_back(inputQ.front());
				inputQ.pop_front();
			}
			inputQ = outputQ;
			outputQ.clear();
		}
		return popNum;
	}

	/** Returns whether the stack is empty. */
	bool empty() {
		if (inputQ.empty()) return true;
		else return false;
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值