Skip to content

Instantly share code, notes, and snippets.

@MichaelSitter
Created January 16, 2018 22:48
Show Gist options
  • Save MichaelSitter/fe01c4a82836766a5dfa0a2cd29cde2b to your computer and use it in GitHub Desktop.
Save MichaelSitter/fe01c4a82836766a5dfa0a2cd29cde2b to your computer and use it in GitHub Desktop.
JS data structures - Stack
'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