day7(用两个栈实现队列)

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
 
提交链接:点击
 
思路:用两个栈实现队列的Push和Pop操作,主要的思路是:先将元素压入stack1,然后再将stack1中的元素出栈压入stack2,这样从stack2出栈的元素顺序就符合元素先入先出的规则了!这里有个需要主要的点,就是元素入栈时,当stack2中还有元素时,不能简单的直接压入stack1。而是应该现将stack2中的元素出栈,重新入栈stack1。然后再将待入栈的元素压入stack1。至于为什么这么做,草稿本画个图就很容易理解了。举个例子,比如 1 2 3 4 5,我们先将1 2 3入队列,然后1出队列,4 5入队列。由于1出队列时候,stack2里面还有2 3。于是4 5入队列的时候,得先将stack2里面的2 3重新入stack1,然后再将4 5入stack1.
 
代码:
class Solution
{
public:
    void push(int node) {
        //栈2不为空,将栈2中的元素重新放入栈1,然后再将node入栈1
        while(!stack2.empty()){
            int temp=stack2.top();
            stack2.pop();
            stack1.push(temp);
        }
        stack1.push(node);
    }

    int pop() {
        //出栈,讲栈1中的元素全部放入栈2中,从栈2取出栈顶
        while(!stack1.empty()){
            int temp = stack1.top();
            stack1.pop();
            stack2.push(temp);
        }
        int result = stack2.top();
        stack2.pop();
        return result;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

非学无以广才,非志无以成学! 【Magic_chao

原文地址:https://www.cnblogs.com/logo-88/p/9658222.html