In a recent coding interview I was asked to solve a problem in which the task was to complete a function which receives a stack as an argument by reference and checks if the passed stack is palindrome or not. I did come up with an approach but it's not at all a good approach according to me.
My Code
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
void copy_it(stack<int> &st, stack<int> &temp) {
if(st.empty())
return;
int element = st.top();
temp.push(element);
st.pop();
copy_it(st, temp);
st.push(element);
}
bool check_palindrome(stack<int> &st, stack<int> &temp) {
if(st.size() != temp.size())
return false;
while(!st.empty()) {
if(st.top() != temp.top())
return false;
st.pop();
temp.pop();
}
return true;
}
int main()
{
vector<int>vec{-1, -2, -3, -3, -2, -1};
stack<int>st;
for(int i = vec.size() - 1; i >= 0; --i) {
st.push(vec[i]);
}
stack<int> temp;
copy_it(st, temp);
cout << check_palindrome(st, temp);
return 0;
}
Is there a better way to do this? I am preferably looking for a recursive algorithm/code.