1. 程式人生 > >LeetCode 之 Implement Queue using Stacks — C++ 實現

LeetCode 之 Implement Queue using Stacks — C++ 實現

Implement Queue using Stacks


Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.
Notes:
  • You must use only standard operations of a stack -- which means only push to top
    peek/pop from topsize, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
利用棧實現佇列的如下操作:
  • push(x) -- 將元素放入隊尾。
  • pop() -- 移除佇列頭的元素。
  • peek() -- 返回佇列頭元素。
  • empty() -- 返回佇列是否為空。
說明:
  • 只能使用棧的標準操作--即push to top, peek/pop from top, size,和 is empty 合法。
  • 使用的語言不一定有棧結構,但可以使用連結串列或佇列模擬棧,只要使用棧的標準操作就可以。
  • 假設所有操作都合法(例如,當佇列空時不會執行 pop 和 peek 操作)。
分析:

    因為棧是 FILO 結構,佇列是 LIFO 結構,入隊操作和壓棧操作一樣,但是出棧操作和出隊操作相反,可以使用輔助棧,出隊時將資料壓入輔助棧,返回棧底(隊頭)元素後再將元素存回原來的棧。

class Queue {
public:
    // Push element x to the back of queue.
    void push(int x) {
        squeue.push(x);
    }

    // Removes the element from in front of queue.
    void pop(void) {
       stack<int> temp;
       stackSwap(squeue, temp);
       temp.pop();
       stackSwap(temp, squeue);
       
       return;
    }

    // Get the front element.
    int peek(void) {
        int ret = 0;
        stack<int> temp;
        stackSwap(squeue, temp);
        ret = temp.top();
        stackSwap(temp, squeue);
        
        return ret;
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return squeue.empty();
    }
    
    void stackSwap(stack<int> &src, stack<int> &dst)
    {
        int srcSize = src.size();
        for(int i = 0; i < srcSize; ++i)
        {
           dst.push(src.top());
           src.pop();
        }
        
        return;
    }
    
private:
    stack<int> squeue;
};