leetcode225和leetcode232

題目

225是用隊列實現棧,232相反javascript

題解

用JavaScript實現好像沒什麼可講的,就是用數組的各類方法。java

代碼

225

var MyStack = function() {
    this.value = []
};

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

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

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

/** * Returns whether the stack is empty. * @return {boolean} */
MyStack.prototype.empty = function() {
    return !this.value.length
};
複製代碼

232

var MyQueue = function() {
    this.value = []
};

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

/** * Removes the element from in front of queue and returns that element. * @return {number} */
MyQueue.prototype.pop = function() {
    return this.value.shift()
};

/** * Get the front element. * @return {number} */
MyQueue.prototype.peek = function() {
    return this.value[0]
};

/** * Returns whether the queue is empty. * @return {boolean} */
MyQueue.prototype.empty = function() {
    console.log(this.value)
    return !this.value.length
};
複製代碼
相關文章
相關標籤/搜索