Created
July 7, 2016 19:41
-
-
Save danielrobertson/5de9a548a033d6af8a94ca610b8765d4 to your computer and use it in GitHub Desktop.
Linked List 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
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