---
# System prepended metadata

title: \#225 Implement Stack using Queues
tags: [leetcode, leetcode-easy]

---

# \#225 Implement Stack using Queues
## *實作資料結構stack(先進後出)*
## Log
 - 20210502 增加使用queue的方式實作解(原題意)
 - build 20210501 by syhuang

## 使用queue的方式實作
 - javascript符合queue動作的方法是shift和push, 這邊限制只能用這兩個方法實作stack
```javascript=
/**
 * Initialize your data structure here.
 */
var MyStack = function() {
    this.queue = [];
};

/**
 * Push element x onto stack. 
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function(x) {
    this.queue.push(x);
};

/**
 * Removes the element on top of the stack and returns that element.
 * @return {number}
 */
MyStack.prototype.pop = function() {
    if(this.empty()) return null;
    //進行push和shift操作, 直到tail元素排在top為止
    for(let i=0; i<this.queue.length-1; i++){
        this.queue.push(this.queue.shift());        
    }
    //把原tail元素(現在在top了)shift出去, 達到使用queue的方式來達成stack.pop操作
    return this.queue.shift();
};

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

/**
 * Returns whether the stack is empty.
 * @return {boolean}
 */
MyStack.prototype.empty = function() {
    if(this.queue.length == 0) return true;
    return false;
};
```
## 初見
 - 用javascript原生方法進行實作
```javascript=
/**
 * Initialize your data structure here.
 */
var MyStack = function() {
    this.items = [];
};

/**
 * Push element x onto stack. 
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function(x) {
    this.items.push(x);
};

/**
 * Removes the element on top of the stack and returns that element.
 * @return {number}
 */
MyStack.prototype.pop = function() {
    if(this.empty()) return null;
    return this.items.pop();
};

/**
 * Get the top element.
 * @return {number}
 */
MyStack.prototype.top = function() {
    if(this.empty()) return null;
    return this.items[this.items.length-1];
};

/**
 * Returns whether the stack is empty.
 * @return {boolean}
 */
MyStack.prototype.empty = function() {
    if(this.items.length == 0) return true;
    return false;
};
```
## 備註
 - 初見時沒注意到題意是要求用"queue"來實作"stack", 也就是說, 在javascript裡只能使用.shift()和.push()做出stack的功能
![](https://i.imgur.com/Gj1lRr0.png)

## 參考
 - [圖片來源](https://realdennis.medium.com/%E4%BD%A0%E5%85%B6%E5%AF%A6%E4%B8%8D%E7%94%A8%E5%9C%A8-javascript-%E5%AF%A6%E4%BD%9C%E4%B8%80%E5%80%8B-queue-b4e788e23bc7)
###### tags: `leetcode`, `leetcode-easy`