Javascript Data Structure Stack Access Nth Top Node

Description

Javascript Data Structure Stack Access Nth Top Node

function Stack(array) {
    this.array = [];/*from www  .  ja v  a 2 s  .co  m*/
    if (array) this.array = array;
}

Stack.prototype.getBuffer = function() {
    return this.array.slice();
}

Stack.prototype.isEmpty = function() {
    return this.array.length == 0;
}

Stack.prototype.peek = function() {
    return this.array[this.array.length - 1];
}


Stack.prototype.push = function(value) {
    this.array.push(value);
}


Stack.prototype.pop = function() {
    return this.array.pop();
};

function stackAccessNthTopNode(stack, n) {
    if (n <= 0) throw 'error'
    
    var bufferArray = stack.getBuffer();
    var bufferStack = new Stack(bufferArray);

    while (--n !== 0) {
        bufferStack.pop();
    }
    return bufferStack.pop();
}

var stack2 = new Stack();
stack2.push(1);
stack2.push(2);
stack2.push(3);
let a = stackAccessNthTopNode(stack2, 2); // 2
console.log(a);



PreviousNext

Related