Created
September 14, 2017 16:13
-
-
Save cixuuz/1a95b2a93367937245f9c39ab6f33821 to your computer and use it in GitHub Desktop.
[234. Palindrome Linked List] #leetcode
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
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