两个栈实现一个队列

  1. 题目描述
    1. 思路

题目描述

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

思路

  • 一个栈stack1专门负责入队,一个栈是stack2专门用于出队
  • 出队的时候,将入队栈中的元素全部压入出队栈,这样出队栈的pop()就等价于队列的pop()
class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        if (stack2.size() == 0){
            while(stack1.size() > 0){
                int item = stack1.top();
                stack1.pop();// pop没有返回值
                stack2.push(item);
            }
        }
        int res = stack2.top();
        stack2.pop();// 先top()获得栈顶元素,再调用pop()弹出栈顶元素
        return res;
    }

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

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1056615746@qq.com

💰

Title:两个栈实现一个队列

Count:175

Author:攀登

Created At:2019-12-26, 23:12:31

Updated At:2024-06-15, 15:53:35

Url:http://jiafeimao-gjf.github.io/2019/12/26/sword-%E4%B8%A4%E4%B8%AA%E6%A0%88%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA%E9%98%9F%E5%88%97/

Copyright: 'Attribution-non-commercial-shared in the same way 4.0' Reprint please keep the original link and author.

×

Help us with donation