Skip to content

Instantly share code, notes, and snippets.

@goldsborough
Created November 12, 2015 21:27
Show Gist options
  • Save goldsborough/6beec6a9dc90591dd19b to your computer and use it in GitHub Desktop.
Save goldsborough/6beec6a9dc90591dd19b to your computer and use it in GitHub Desktop.
Checks if a list is a palindrome.
template<typename Node>
bool _is_palindrome(Node* left, Node*& right, bool& move_back)
{
if (left != right)
{
if (! _is_palindrome(left->next, right, move_back)) return false;
}
if (! move_back)
{
if (left->data != right->data) return false;
right = right->next;
}
else move_back = false;
return true;
}
template<typename Node>
bool is_palindrome(Node* node)
{
if (! node || ! node->next) return false;
auto turtle = node;
auto hare = node;
std::size_t count = 0;
while (hare)
{
turtle = turtle->next;
hare = hare->next->next;
++count;
}
bool move_back = count % 2 == 0;
return _is_palindrome(node, turtle, move_back);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment