1. 程式人生 > >LeetCode 225 Implement Stack using Queues(用隊列來實現棧)(*)

LeetCode 225 Implement Stack using Queues(用隊列來實現棧)(*)

using man mean leetcode == peek uil erl end

翻譯

用隊列來實現棧的例如以下操作。

push(x) —— 將元素x加入進棧 pop() —— 從棧頂移除元素 top() —— 返回棧頂元素 empty() —— 返回棧是否為空 註意: 你必須使用一個僅僅有標準操作的隊列。 也就是說,僅僅有push/pop/size/empty等操作是有效的。

隊列可能不被原生支持。這取決於你所用的語言。 僅僅要你僅僅是用queue的標準操作,你能夠用list或者deque(double-ended queue)來模擬隊列。

你能夠如果全部的操作都是有效的(比如,pop或peek操作不會被用在空棧上)。

原文

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).

分析

對棧和隊列不清楚的話。能夠先看這篇圖文介紹:【算法】7 分不清棧和隊列?一張圖給你完總體會

至於這道題目。有一道很很相似的題目。

本題是用隊列來實現棧,以下這題是用棧來實現隊列。由於在上一篇中解說過,原理是一樣的,大家能夠自己看看:LeetCode 232 Implement Queue using Stacks(用棧來實現隊列)(*)

代碼

class Stack {
public:
    queue<int> q, q2;

    // Push element x onto stack.
    void push(int x) {
        q.push(x);
    }

    // Removes the element on top of the stack.
    void pop() {
        if (q.size() == 1) q.pop();
        else {
            while (q.size() > 1) {
                q2.push(q.front());
                q.pop();
            }
            q.pop();
            while (q2.size() > 0) {
                q.push(q2.front());
                q2.pop();
            }
        }
    }

    // Get the top element.
    int top() {
        if (q.size() == 1) return q.front();
        while (q.size() > 1) {
            q2.push(q.front());
            q.pop();
        }
        int temp = q.front();
        q2.push(q.front());
        q.pop();
        while (q2.size() > 0) {
            q.push(q2.front());
            q2.pop();
        }
        return temp;
    }

    // Return whether the stack is empty.
    bool empty() {
        return q.empty();
    }
};

LeetCode 225 Implement Stack using Queues(用隊列來實現棧)(*)