原题链接在这里:https://leetcode.com/problems/palindrome-linked-list/
思路: 原题要求time O(n), space O(1). 所以不能用额外空间。先找到中点,reverse中点后面的list部分,再与head开始逐个比较 val. 期中reverse部分可以参见Reverse Linked List中的Method 2.
AC Java:
/**
* 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 walker = head;
ListNode runner = head;
while(runner.next != null && runner.next.next != null){
runner = runner.next.next;
walker = walker.next;
}
ListNode middleHead = walker.next;
middleHead = reverseList(middleHead);
while(head != null && middleHead != null){
if(head.val != middleHead.val){
return false;
}
head = head.next;
middleHead = middleHead.next;
}
return true;
}
private ListNode reverseList(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode tail = head;
ListNode cur = head;
ListNode pre;
ListNode temp;
while(tail.next!=null){
pre = cur;
cur = tail.next;
temp = cur.next;
cur.next = pre;
tail.next = temp;
}
return cur;
}
}