Javascript Data Structure Stack 3

Description

Javascript Data Structure Stack 3

function Stack() { 
   this.dataStore = []; /*from   w  w w .j av a 2  s  .  co  m*/
   this.top = 0; 
   this.push = push; 
   this.pop = pop; 
   this.peek = peek; 
   this.clear = clear; 
   this.length = length; 
} 

function push(element) { 
   this.dataStore[this.top++] = element; 
} 

function peek() { 
   return this.dataStore[this.top-1]; 
} 

function pop() { 
   return this.dataStore[--this.top]; 
} 

function clear() { 
   this.top = 0; 
} 

function length() { 
   return this.top; 
} 
let s = new Stack(); 
s.push("A"); 
s.push("B"); 
s.push("C"); 
console.log("length: " + s.length()); 
console.log(s.peek()); 
let popped = s.pop(); 
console.log("The popped element is: " + popped); 
console.log(s.peek()); 
s.push("D"); 
console.log(s.peek()); 
s.clear(); 
console.log("length: " + s.length()); 
console.log(s.peek()); 
s.push("E"); 
console.log(s.peek()); 



PreviousNext

Related