【一天一道LeetCode】#225. Implement Stack using Queues

时间:2023-03-09 02:00:21
【一天一道LeetCode】#225. Implement Stack using Queues

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

(一)题目

Implement the following operations of a stack using queues.

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • empty() – Return whether the stack is empty.

Notes:

  • You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack)

(二)解题

题目大意:用queue来实现一个stack。

解题思路:queue是先进先出,stack是先进后出。采用一个queue就能实现stack

push:直接压入到queue

pop:需要弹出queue的尾元素,可是queue只能弹出queue的头元素。这时候可以把queue的头元素弹出再压入queue,一直到尾元素弹出即可

top:直接利用queue的back()即可知道stack顶元素

empty:判断queue是否为空。

class Stack {
public:
    // Push element x onto stack.
    void push(int x) {
        que.push(x);
    }

    // Removes the element on top of the stack.
    void pop() {
        int size = que.size();
        for(int i = 0 ; i < size-1 ;i++){//queue的头元素弹出再压入,直到尾元素弹出
            que.push(que.front());
            que.pop();
        }
        que.pop();
    }

    // Get the top element.
    int top() {
        return que.back();
    }

    // Return whether the stack is empty.
    bool empty() {
        if(que.empty()) return true;
        return false;
    }
private:
    queue<int> que;
};