Skip to content

Instantly share code, notes, and snippets.

@nemtsov
Last active December 15, 2015 02:08
Show Gist options
  • Save nemtsov/5184637 to your computer and use it in GitHub Desktop.
Save nemtsov/5184637 to your computer and use it in GitHub Desktop.
/**
* Stack
* LIFO data structure
*/
exports.Stack = Stack;
exports.Stack1 = Stack1;
exports.Stack2 = Stack2;
exports.Stack3 = Stack3;
function Stack() {
this._top = new Entry(undefined, this._top);
}
Stack.prototype.peek = function () {
return this._top.value;
};
Stack.prototype.pop = function () {
var value = this._top.value;
this._top = this._top.prev;
return value;
};
Stack.prototype.push = function (value) {
this._top = new Entry(value, this._top);
};
function Entry(value, prev) {
this.value = value;
this.prev = prev;
}
function Stack1() {
var top = {value: undefined , prev: top};
function pop() {
var value = top.value;
top = top.prev;
return value;
}
function push(value) {
top = {value: value , prev: top};
}
Object.defineProperty(this, 'pop', { value: pop });
Object.defineProperty(this, 'push', { value: push });
}
function Stack2() {
var stack = []
, len = 0;
function pop() {
if (0 === len) return;
len--;
var value = stack[len];
delete stack[len];
return value;
}
function push(value) {
stack[len] = value;
len++;
}
Object.defineProperty(this, 'pop', { value: pop });
Object.defineProperty(this, 'push', { value: push });
}
function Stack3() {
var stack = []
, len = 0;
function pop() {
return stack.pop();
}
function push(value) {
stack.push(value);
}
Object.defineProperty(this, 'pop', { value: pop });
Object.defineProperty(this, 'push', { value: push });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment