My function is a recursive function to delete the middle element of a stack. The coding platform has already given it's implementation of a stack which means I have access to the push() and pop() method.
I want to pop() till I reach the middle ele and then push the popped elements back.
However, if I store the pop, it shows up as undefined.
If I console.log the pop call, it returns undefined.
class Solution
{
solve(s,midEle) {
let self = this;
if(midEle===1){
s.pop();
return;
}
let temp = s.pop();
self.solve(s,midEle-1);
s.push(temp)
return
}
//Function to delete middle element of a stack.
deleteMid(s, sizeOfStack)
{
// code here
const mid = Math.ceil((sizeOfStack+1)/2);
this.solve(s,mid);
}
}
It is because you are returning nothing:
return;
In javascript, the value of nothing is undefined. Thus the code above returns the value undefined.
To return the value you popped from the array, simply return it:
var item = s.pop();
return item;
or more simply:
return s.pop();