---
# System prepended metadata

title: \#232 Implement Queue using Stacks
tags: [leetcode, leetcode-easy]

---

# \#232 Implement Queue using Stacks
## *使用stack的資料結構實作queue*
## Log
 - build 20210508 by syhuang

## xxx
 - xxx
```javascript=
```
## 初見
 - 使用javascript原生的stack方法(.shift()和.unshift())實作queue
```javascript=
/**
 * Initialize your data structure here.
 */
var MyQueue = function() {
    this.queue = [];
};

/**
 * Push element x to the back of queue. 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this.queue.unshift(x);
};

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    //限制使用stack方法(.unshift()和.shift())實作queue)
    if(this.empty()) return null;
    var t = [];
    var len = this.queue.length;
    for(let i=0; i<len-1; i++){
        t.unshift(this.queue.shift());
    }
    len = t.length;
    var result = this.queue.shift();    
    for(let i=0; i<len; i++){
        this.queue.unshift(t.shift());
    }
    
    return result;
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    if(this.empty()) return null;
    return this.queue[this.queue.length-1];
};

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return this.queue.length==0;
};
```
## 備註
 - 與#225類似
## 參考
###### tags: `leetcode`, `leetcode-easy`