Last active
May 15, 2016 06:16
-
-
Save Williammer/0664978c9448ea413979de131d13bd5e to your computer and use it in GitHub Desktop.
Stack data structure in javaScript.
This file contains 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
function Stack() { | |
// this._size = 0; | |
// this._storage = {}; | |
this._storage = []; // array could be more performant due to array browser optimize | |
} | |
Stack.prototype.push = function (data) { | |
// var size = ++this._size; | |
var len = this._storage.length; | |
this._storage[len] = data; | |
}; | |
Stack.prototype.peek = function () { | |
var len = this._storage.length; | |
return this._storage[len-1]; | |
}; | |
Stack.prototype.clear = function () { | |
this._storage.length = 0; | |
}; | |
Stack.prototype.pop = function () { | |
var len = this._storage.length, | |
deletedData; | |
if (len > 0) { | |
deletedData = this._storage[this._storage.length--]; | |
// delete this._storage[size]; | |
// this._storage[size] = null; // set to null clear mem than delete. | |
// this._size--; | |
return deletedData; | |
} | |
}; |
This file contains 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
var stack = []; | |
// first in | |
stack.push("a"); | |
stack.push("b"); | |
// last out | |
stack.pop(); // "b" |
This file contains 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
var Stack = function () { | |
this.top = null; | |
this.size = 0; | |
}; | |
var Node = function (data) { | |
this.data = data; | |
this.previous = null; | |
}; | |
Stack.prototype.push = function (data) { | |
var node = new Node(data); | |
node.previous = this.top; | |
this.top = node; | |
this.size += 1; | |
return this.top; | |
}; | |
Stack.prototype.pop = function () { | |
temp = this.top; | |
this.top = this.top.previous; | |
this.size -= 1; | |
return temp; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment