Created
January 16, 2018 22:48
-
-
Save MichaelSitter/fe01c4a82836766a5dfa0a2cd29cde2b to your computer and use it in GitHub Desktop.
JS data structures - Stack
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
'use strict'; | |
function Node(item) { | |
this.value = item; | |
this.next = null; | |
} | |
function Stack() { | |
this.items = null; | |
} | |
Stack.prototype.push = function (item) { | |
var node = new Node(item); | |
if (this.items === null) { | |
this.items = node; | |
} else { | |
node.next = this.items; | |
this.items = node; | |
} | |
}; | |
Stack.prototype.peek = function () { | |
return this.items.value; | |
}; | |
Stack.prototype.pop = function () { | |
if (this.items === null) { | |
throw new Error('out of range'); | |
} | |
var val = this.items.value; | |
this.items = this.items.next; | |
return val; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment