In C++ programme, let's analyse stack data structure. My question is : Is it possible to check if the given stack contains palindrome or not WITHOUT ANY additional data structure and without modifying the stack? You are allowed to decompose the stack so long as you put it back together again (I mean that by modifying).
Example 1: s = {1, 2, 3, 2, 1} - it's palindrome Example 2: s = {1, 2, 3, 4, 5} - it's not a palindrome
void checkStack(Stack<int>& s){
//Exit condition
if(s.numberOfElements() == 0){
return;
}
int temp = s.pop();
checkStack(s);
s.push(temp);
}
Is it possible to check if word stored on stack is palyndrome without ANY additonal data structures in C++
I think that you mean by data structures some other abstract data structures or containers like list, vector and so on.
You can do your task by enclosing in a wrapper the standard class std::stack<int>
.
For example
#include <iostream>
#include <iomanip>
#include <stack>
#include <iterator>
#include <algorithm>
bool is_palindrome( const std::stack<int> &st )
{
struct wrapper : std::stack<int>
{
wrapper( const std::stack<int> &st ) : std::stack<int>( st ) {}
bool is_palindrome() const
{
return std::equal( std::begin( c ), std::next( std::begin( c ), c.size() / 2 ),
std::rbegin( c ) );
}
} w( st );
return w.is_palindrome();
}
int main()
{
std::stack<int> st1( std::stack<int>::container_type{ 1, 2, 3, 2, 1 } );
std::cout << std::boolalpha << is_palindrome( st1 ) << '\n';
std::stack<int> st2( std::stack<int>::container_type{ 1, 2, 3, 4, 5 } );
std::cout << std::boolalpha << is_palindrome( st2 ) << '\n';
return 0;
}
The program output is
true
false
The class wrapper
has an access to the protected data member c
of the class std::stack<int>
that denotes the underlying container.