剑指offer JZ-5

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
 

思路

比较简单,stack1用来存放每次push进来的数据

栈是先进后出的数据结构,而队列是先进先出的数据结构

在用栈模拟队列的pop时,将stack1弹出的元素暂时存放在stack2中

在stack1弹出最早压入栈中的元素后,再将stack2的中的元素一一弹出,并压入stack1中即可

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        int Size = stack1.size();
        while(Size > 1)
        {
            int val = stack1.top();
            stack1.pop();
            stack2.push(val);
            Size--;
        }
        int val = stack1.top();
        stack1.pop();
        while(!stack2.empty())
        {
            stack1.push(stack2.top());
            stack2.pop();
        }
        return val;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};
View Code
原文地址:https://www.cnblogs.com/alan-W/p/14226520.html