Created
November 12, 2015 21:27
-
-
Save goldsborough/6beec6a9dc90591dd19b to your computer and use it in GitHub Desktop.
Checks if a list is a palindrome.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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