By "linked list" do you mean std::list ?
template <typename BiDiIterator> bool isPalindrome(BiDiIterator first, BiDiIterator last) { if (first == last) return true; --last; if (first == last) return true; if (*first != *last) return false; return isPalindrome(++first, last);
I used the fact that it is possible to iterate from the end as well as forward from the very beginning. It is unclear whether this is being asked.
With a singly linked list, you can run two iterators, one fast and one slow. For each call, increase speed once and slow once. When fast reaches the end of the list, slow is at the midpoint (um, +/- 1 and takes into account lists of odd length and even length). At this point, return from your recursion by comparing character values. & Theta; (n) complexity for use during operation and memory (not recursive).
I would write the code, but it's time to sleep here in the UK.
[Edit: morning all
template <typename FwdIterator> std::pair<FwdIterator, bool> isPalindrome(FwdIterator slow, FwdIterator fast, FwdIterator last) { if (fast == last) return std::make_pair(slow, true); ++fast; if (fast == last) return std::make_pair(++slow, true); ++fast; FwdIterator next = slow; std::pair<FwdIterator, bool> result = isPalindrome(++next, fast, last); if (result.second == false) return result; if (*slow != *(result.first)) return std::make_pair(slow, false); ++(result.first); return result; } ... isPalindrome(mylist.begin(), mylist.begin(), mylist.end()).second;
If for some bizarre reason your linked list does not provide an iterator, then hopefully the equivalent code with if (fast->next == 0) , fast = fast->next , etc. obvious. And of course, you can remove the user interface with a wrapper.
I think you can avoid additional storage if you are allowed to temporarily change the list by flipping the list to "slow" when you go down, and then turn it over again when you go up. Thus, you do not need to store a copy of slow on a recursive call: instead, you can return an extra pointer for a subsequent call. However, I will not worry.
]