Skip to content

Instantly share code, notes, and snippets.

@matteogobbi
Created July 26, 2015 21:35
Show Gist options
  • Save matteogobbi/fb4d89e91f574f8bd80e to your computer and use it in GitHub Desktop.
Save matteogobbi/fb4d89e91f574f8bd80e to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) return true;
ListNode faster = head;
Stack<Integer> values = new Stack<Integer>();
// Reach the middle with head
while (faster.next != null && faster.next.next != null) {
values.push(head.val);
faster = faster.next.next;
head = head.next;
}
// Check if push the middle element or not
if (faster.next != null) {
values.push(head.val);
}
while (head.next != null) {
head = head.next;
if (head.val != values.pop()) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment