Skip to content

Instantly share code, notes, and snippets.

@danielrobertson
Created July 7, 2016 19:41
Show Gist options
  • Save danielrobertson/5de9a548a033d6af8a94ca610b8765d4 to your computer and use it in GitHub Desktop.
Save danielrobertson/5de9a548a033d6af8a94ca610b8765d4 to your computer and use it in GitHub Desktop.
Linked List Palindrome
boolean isPalindrome(Node n){
Node fast = n;
Node slow = n;
// push first half onto stack, then compare with second half
Stack<Integer> s = new Stack<Integer>();
while(fast != null && fast.next != null) {
s.push(slow.data);
slow = slow.next;
fast = fast.next.next;
}
// if odd length, skip middle element since it doesn't matter for palindromes
if(fast != null) {
slow = slow.next;
}
while(slow != null) {
int popped = s.pop();
if(popped != slow.data) {
return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment