To be honest, I am pretty sure that you do not quote the task description fully correct. Several things are fishy about the task...
For one, one could do some hairsplitting and argue that it is impossible to use a std::stack
without using any other data structure. A std::stack
is just a container adapter that is build upon some underlying container. The default is a std::deque
. Strictly speaking, using a std::stack
without using any other data structure makes no sense.
Next, you are not allowed to modify the stack, but you are allowed to decompose it, as long as you put it back together again. This basically allows you to do anything. What I mean is, that you can for example write a function that returns you the nth element, eg:
int access(std::stack<int> s, size_t i) {
while (i--) s.pop();
return s.top();
}
Using this it is kind of trivial to write a test for palindrome. However this is basically treating the stack as if it wasn't a stack. For a similar approach that bypasses the stackyness of the std::stack
see this answer.
Note that for the little cheat above I had to make a copy of the stack (s
is passed by value) and I cannot imagine a solution, even a recursive one, that would not use at least a second stack. When you decompose the stack you need to store the elements somewhere, otherwise how would you restore it afterwards?
Let's forget about the exact task for a moment and consider how can we check if a std::stack
contains a palindrome (without the unclear constraints), then one simple solution would be
bool check_palindrome(std::stack<int>& s) {
std::stack<int> t;
while (t.size() < s.size()) {
auto temp = s.top();
s.pop();
t.push(temp);
}
if (t.size() > s.size()) t.pop();
return s==t;
}
This could also be turned into a recursive method (to be honest I dont really get the hype about recursion), but I wouldn't know how to do it without the second stack. Also I didn't bother to reconstruct the original stack, but it would be easy to do so.