Created
May 29, 2017 17:05
-
-
Save rebeccapeltz/2e5ecd3038158e0149c5385145c3a787 to your computer and use it in GitHub Desktop.
Implement a stack by wrapping a JavaScript array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
var Stack = function() { | |
this._arr = []; | |
this.top = null; | |
this.size = this._arr.length; | |
}; | |
Stack.prototype.push = function(data) { | |
this._arr[this.size] = data; | |
this.size += 1; | |
this.top = this._arr[this.size - 1]; | |
}; | |
Stack.prototype.pop = function() { | |
let temp = this.top || null; //deal with empty stack | |
this.size = this.size === 0 ? 0 : --this.size; | |
this.top = this.size === 0 ? null : this._arr[this.size - 1]; | |
return temp; | |
}; | |
Stack.prototype.peek = function() { | |
if (this.top) return this.top | |
else return null; | |
} | |
let stack = new Stack(); | |
stack.push(1); | |
stack.push(2); | |
console.log("peek",stack.peek()); | |
console.log("pop",stack.pop()); | |
console.log("peek after pop", stack.pop()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment