# 232. Implement Queue using Stacks

## 1.問題

* 用stack來設計queue

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LJdKtXVjMD8bUOUDOXZ%2F-LJdMSqTp88q7FwGntEP%2F2018081105.jpg?alt=media\&token=c820082d-3375-4014-95bd-e0affda3dcb0)

## 2.想法

* 當push時, 將所有reverseStack中的元素推入forwardStack;
* 當pop時, 將所有forwardStack中的元素推入reverseStack
* empty要確定兩個stack都是empty

## 3.程式碼

```
class MyQueue {
public:
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        if (forwardStack.empty()) {
            while (!reverseStack.empty()) {
                forwardStack.push(reverseStack.top());
                reverseStack.pop();
            }
        }
        forwardStack.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if (reverseStack.empty()) {
            while (!forwardStack.empty()) {
                reverseStack.push(forwardStack.top());
                forwardStack.pop();
            }
        }
        int top = reverseStack.top();
        reverseStack.pop();
        return top;
    }
    
    /** Get the front element. */
    int peek() {
        if (reverseStack.empty()) {
            while (!forwardStack.empty()) {
                reverseStack.push(forwardStack.top());
                forwardStack.pop();
            }
        }
        int top = reverseStack.top();
        return top;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return forwardStack.empty() && reverseStack.empty();
    }
private:
    stack<int> forwardStack;
    stack<int> reverseStack;
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * bool param_4 = obj.empty();
 */
```

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LJdKtXVjMD8bUOUDOXZ%2F-LJdMz9U3FLFqhxn72PG%2F2018081106.jpg?alt=media\&token=e9dcb6e8-c6a3-42f5-bed3-0a28c3027f52)
