Searching a word forward and backward (palindromes)

Sep 15, 2011 at 2:31pm
I need write a function that goes through a linked list and see if the words in the list are palindromes. So, I need to go through the letters in the word one way and compare that with going through the letters of the word the opposite way and if they match then the word is a palindrome and I return true.

This function takes the head and the tail of the doubly linked list and returns true if the string is a palindrome, false otherwise.

example: racecar = racecar;


1
2
3
4
5
6
7
bool isPalindrome(CharLinkD * head, CharLinkD * tail) {
	bool answer = true;



	return answer;
}


What I'm confused about is how to I compare the same word forwards and backwards?
Thanks
Sep 15, 2011 at 2:49pm
You have the head and the tail of the list (I suppose the list values are chars?) -
just go this way:
1) if head and tail are the same element, it's a palindrome
2)otherwise:
2.1)is tail the predecessor of head?
2.1.1) if yes, it is a palindrome
2.1.2) if no, are the values of head and tail the same?
2.1.2.1) if yes, set head to head->next and tail to tail->prev, and then go back to 1
2.1.2.2) if no, it is not a palindrome.

just try to do this on paper, and you will see how it works.
Sep 15, 2011 at 2:55pm
Hi,

here is a function to check if a string is a pallindrome:

1
2
3
4
5
6
7
8
9
10
#include <string>
#include <algorithm>

using std::string;
using std::equal;

bool is_pallindrome(const string& s)
{
  return equal(s.begin(), s.end(), s.rbegin());
}


Edit: Oops, looks like I misunderstood you, sorry about that!

I hope that helps.
Last edited on Sep 15, 2011 at 2:59pm
Sep 15, 2011 at 2:59pm
@dangrr888

read this: http://www.cplusplus.com/forum/beginner/1/ especially the answer part, and this:
http://www.cplusplus.com/forum/articles/31015/
Last edited on Sep 15, 2011 at 3:00pm
Sep 15, 2011 at 3:02pm
Thanks hanst99, it seems much simplier in my head but I'll try to put it in code and see how it works out.

Also, thats for your good intentions dangrr888.
Topic archived. No new replies allowed.