Question:
palindrome dev c++ using stack?
anonymous
2011-02-16 21:38:37 UTC
palindrome dev c++ using stack
Three answers:
Cubbi
2011-02-17 03:52:04 UTC
That's not enough to make a full question. Guessing what you want is a function that returns true if a given string is a palindrome, I'd say you could do something like



#include

#include

bool palindrome(const std::string& s)

{

     std::stack st;

     for(size_t i=0; i
         st.push(s[i]);

     for(size_t i=0; i
     {

         if(st.top() != s[i])

             return false;

         st.pop();

     }

     return true;

}



but it sounds like a very strange way to do it since you can check that much faster and simpler with equal()



#include

#include

bool palindrome(const std::string& s)

{

     return equal(s.begin(), s.end(), s.rbegin());

}



or with the plain operator==



#include

bool palindrome(const std::string& s)

{

     return s == std::string(s.rbegin(), s.rend());

}
?
2016-02-27 04:24:12 UTC
You want a stack not a queue... Google how to create a stack in C, it'll be good practice. The palindrome crap is trivial, but learning what a stack is and how to implement it is very important. Also you need to be able to answer the question WHY do you need a stack and not a queue for this...
anonymous
2011-02-16 22:04:39 UTC
I've done this in java, but the way of solving the problem is the same

first, each character of the String onto a stack

then pop each character off and compare each character to each character in String



This is what I did in Java:

public boolean palindrome(String string)

{

MyStack myStack = new MyStack();

String split[] = string.split(" "); // split the string by spaces

for (int i = 0; i < split.length; i++)

{

myStack.push(new StackNode(split[i])); // add each character to stack

}

for (int j = 0; j < split.length; j++)

{

String compare = myStack.pop().getData();

if (!compare.equals(split[i]))

return false;

}

if (myStack.pop() != null)

return false;

return true;

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...