creating a new Stack - Node.js Data Structure

Node.js examples for Data Structure:Stack

Description

creating a new Stack

Demo Code


 //creating a new Stack
var Stack = function() {
    this.length = -1;//from   w w w  .  jav  a2s.  c o m
    this.value = [];
};

/**
 * @param {number} x
 * @returns {void}
 */
Stack.prototype.push = function(x) {

   this.length++;
   
   this.value[this.length] = x;
};

/**
 * @returns {void}
 */
Stack.prototype.pop = function() {
    //if Stack is empty
    if(this.value < 0){
        return null;
    }
    //top element
    var topElement = this.value[this.length];
    this.length--;
    //reduce last element of the array
    this.value.length--;
    
    return topElement
};

/**
 * @returns {number}
 */
Stack.prototype.top = function() {
    if(this.length < 0){
        return [];
    }
    return this.value[this.length];
};

/**
 * @returns {boolean}
 */
Stack.prototype.empty = function() {
   
   return this.length < 0 ? true: false;
    
};

Related Tutorials