思路:
(1)快慢指针找到链表的中点;
(2)后半段反转;
(3)前后半段一一比较,看是否构成回文串。
java code:
/**
* 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;
//find the mid ListNode
ListNode fast = head, slow = head;
while(fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
//reverse the mid - last ListNode
ListNode last = slow.next, pre = head;
while(last.next != null) {
ListNode tmp = last.next;
last.next = tmp.next;
tmp.next = slow.next;
slow.next = tmp;
}
//compare
while(slow.next != null) {
slow = slow.next;
if(pre.val != slow.val) return false;
pre = pre.next;
}
return true;
}
}