LeetCode 232. 用栈实现队列

题目描述

使用栈实现队列的下列操作:

  • push(x) -- 将一个元素放入队列的尾部。
  • pop() -- 从队列首部移除元素。
  • peek() -- 返回队列首部的元素。
  • empty() -- 返回队列是否为空。

思路

创建两个栈 s1, s2

  1. 入队

    将元素放入 s1 中

  2. 出队

    • 若 s2 为空,将 s1 的元素 放入 s2 中, 此时 s2 的栈顶就是队首元素,s2 栈顶出栈。
    • 若 s2 不为空,直接将 s2 栈顶元素出栈即可。
  3. 获取队首元素

    • 若 s2 不为空,s2 的栈顶元素就是队首元素。
    • 若 s2 为空,s1 不为空,将 s1 中的元素放入 s2 中,然后 s2 的栈顶元素就是队首元素。
class MyQueue {
public:
    /** Initialize your data structure here. */
    stack<int> s1, s2;
    int temp;
    int res;
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        s1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if(s2.empty())
        {
            while(!s1.empty())
            {
                temp = s1.top();
                s2.push(temp);
                s1.pop();
            }
            res = s2.top();
            s2.pop();
            return res;
        }
        else
        {
            res = s2.top();
            s2.pop();
            return res;
        }
    }
    
    /** Get the front element. */
    int peek() {
        if(!s2.empty())
        {
            res = s2.top();
            return res;
        }
        else if(!s1.empty())
        {
            while(!s1.empty())
            {
                temp = s1.top();
                s2.push(temp);
                s1.pop();
            }
            res = s2.top();
            return res;
        }
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return s1.empty() && s2.empty();
    }
};

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 空闲 或是久来的困扰 找寻 发现了未知的世界 明白 不敢久留 偷偷地 窥视着里面的一切 慢慢地 烂熟于心 ...
    翻跟斗的小白阅读 1,092评论 0 0
  • 亲爱的家人们,我分享一个今天晚上发生在我家的故事。晚饭时母亲和我说了一件事情:早上,妈妈打电话给她的妹妹提供一个信...
    云栖1978阅读 1,560评论 0 0
  • 每当寒冬来临,百花大多都枯萎了或者躲进泥土被子里睡大觉了,他们都害怕严寒,不愿在冬天开花,给人们一丝美的享受。这是...
    呆萌妹子拽天下_9778阅读 2,958评论 0 0