Skip to content

Instantly share code, notes, and snippets.

@jason51122
Created July 3, 2014 04:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jason51122/ca90d321da5a21c80ed1 to your computer and use it in GitHub Desktop.
Save jason51122/ca90d321da5a21c80ed1 to your computer and use it in GitHub Desktop.
2.7 Implement a function to check if a linked list is a palindrome.
public boolean linkedListPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode slow = head;
ListNode fast = head;
Stack<Integer> s = new Stack<Integer>();
s.push(slow.val);
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
s.push(slow.val);
}
// The number of nodes is odd when fast is the last.
if (fast.next == null) {
s.pop();
}
slow = slow.next;
while (slow != null) {
if (s.pop() != slow.val) {
return false;
}
slow = slow.next;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment