Rise and Shine. One more day playing with recursion. I tried solving two new problems that I found out. However, I wasn't able to solve the second one. But still, I got this one down. In this case, I was asked to remove the middle element of the stack.
Stacks are data structures that are stored in a manner like a pile of books one over the other. And the book at the top of all will be the first to be taken out. That very similar logic I applied to solve this problem. I kept storing elements in some memory locations until I removed the middle element and after removing the middle element. I started putting those elements back into the stack.
class Solution
{
public:
//Function to delete middle element of a stack.
void solve(stack<int>&st, int sizeOfStack, int count){
if(count == sizeOfStack/2){
st.pop();
return;
}
int num = st.top();
st.pop();
solve(st, sizeOfStack, count+1);
st.push(num);
}
void deleteMid(stack<int>&s, int sizeOfStack)
{
int count = 0;
solve(s, sizeOfStack, count);
}
};