Created
July 26, 2015 21:35
-
-
Save matteogobbi/fb4d89e91f574f8bd80e to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* 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