Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Created September 14, 2017 16:13
Show Gist options
  • Save cixuuz/1a95b2a93367937245f9c39ab6f33821 to your computer and use it in GitHub Desktop.
Save cixuuz/1a95b2a93367937245f9c39ab6f33821 to your computer and use it in GitHub Desktop.
[234. Palindrome Linked List] #leetcode
class Solution {
// O(n) O(1)
public boolean isPalindrome(ListNode head) {
ListNode rev = null, tmp = null;
ListNode fast = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
tmp = rev;
rev = head;
head = head.next;
rev.next = tmp;
}
ListNode tail = (fast != null) ? head.next : head;
boolean isPali = true;
while (rev != null) {
isPali = isPali && rev.val == tail.val;
tmp = head;
head = rev;
rev = rev.next;
head.next = tmp;
tail = tail.next;
}
return isPali;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment