MOD 4 - STACK

by SHELDON PASCIAK

JavaScript

function Stack() { 
    this.top = null;
    this.size = 0;
}

function Node(data) {
    this.data = data;
    this.previous = null;    
}

//create new node making it the new top node 
Stack.prototype.push = function(value) { 
	  console.log(value);
    var node = new Node(value);  
    node.previous = this.top;
    this.top = node;
    this.size ++;    
    return this.top;
};

//retrieve top value, don't remove node
Stack.prototype.peek = function() {
    if (this.size>0) {  
        temp = this.top;
        console.log(temp.data);
        return temp.data;
    } else {
        //The stack did not contain enough values or is EMPTY.
        alert("The stack did not contain enough values or is EMPTY.");
        return null;   
    }
};

//return the value at the top node, removing top node in the process
Stack.prototype.pop = function() {

    if (this.size>0) {  
        temp = this.top;
        this.top = this.top.previous;
        this.size -= 1; 
        console.log(temp.data);
        return temp.data;
        
    } else {    
        alert("The stack did not contain enough values or is EMPTY.");
        return null;   
    }
};

//boolean to check if stack is empty
Stack.prototype.isEmpty = function() { 
    return (this.size<=0);
}

//show all values top to last
Stack.prototype.print = function() {
    console.log("----[ print ] ------");
    var current=this.top;
    while (current) {             
    console.log(current.data);
    current = current.previous; // becomes null at top   
    }
    console.log("----[ end of print ] ------");
}

var myStack = new Stack();

myStack.push(1);
myStack.push(2);

myStack.pop();
myStack.pop();

console.log("\n\n-----\n\n");

myStack.push(5);
myStack.push(15);
myStack.push(35);

myStack.print();

myStack.pop();
myStack.pop();
myStack.peek();
myStack.peek();
myStack.pop();