Data structures and algorithms


Image result for stack.pop



Stacks


Stack.push:  The stack.push places the data on the top and the rest are queued.




Stack.pop: The pop method removes the top data instead of the bottom.


stack.peek: Displays the top data


stack.length: Displays the # of data inside an array or object.


Ex 1.)

var letters = [];         [] === arrays where the data is going to be stored

var word = "101"

var rword = "";

// put letters of word into stack
for (var i = 0; i < word.length; i++) {         This will push the letters in the string
   letters.push(word[i]);
}

// pop off the stack in reverse order
for (var i = 0; i < word.length; i++) {         This will pop the letters in the pushed output
   rword += letters.pop(); 
}

if (rword === word) {
   console.log(word + " is a palindrome.");   This will determine if the word is a                                                                          palindrome            
}
else {
   console.log(word + " is not a palindrome.");
}



Of course computers can't read random words such as pop or push. Those words are just a mere abstraction and we need to implement the code.



var Stack = function() {                     This creates the stack function
    this.count = 0;
    this.storage = {};


  this.push = function(value) {
        this.storage[this.count] = value;    This adds the value into the data
        this.count++;
    }


 this.pop = function() {
        if (this.count === 0) {
            return undefined;
        }

        this.count--;
        var result = this.storage[this.count];   This removes and returns the value at the                                                               end of the stack
 delete this.storage[this.count];
        return result;
    }
    
    this.size = function() {
        return this.count;
    }











Comments

Popular posts from this blog

Code

Acknowledgement