OneCompiler

data structures stack

145

class stack{
constructor(size){
if(isNaN(size)){
size = 4
}
//declaring empty array,size and initial value 0

this.size = size
this.arr = []
this.top = 0
this.end = this.arr.length-1

}
//declaring 3 methods
push(elem){
//iftopisbiggerthansizethanitsoverflow
if(this.top>this.size){
return console.log(stack is overflow)
}
else{
//transfer the value from elem to arr
this.arr[this.top]=elem;
this.top = this.top+1;
// console.log((this.top))
return(this.arr)

}

}

pop(){

if(this.top == 0){
  return console.log(`stack is underflow`)
}

else 
{
  
  this.arr=this.arr.slice(0,this.arr.length-1)
  console.log("pop",this.arr.length)
  this.top = this.top-1
  
  console.log("pop",`[ ${this.arr} ]`)
  return this.arr
} 

}

search(element){
let arr1 = [...this.arr]
let top = this.arr.length-1
if(top==-1){
return -1;
}
else{
for(let i = 0;i<arr1.length;i++){
let x = arr1[top]
top = top-1
if(x==element){
return true
}
}
return false
}
}
}

let s1 = new stack(4)
console.log(s1.push(2))
console.log(s1.push(3))
console.log(s1.push(10))
s1.pop()
s1.pop()

console.log(s1.search(5))
console.log(s1.search(2))
console.log(s1.search(3))