/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode fast = head,slow = head;
// 通过快慢指针找到中点
while(fast != null && fast.next != null){ // fast 不是null和最后一个
fast = fast.next.next;//1+2*k // * * * * * * *
slow = slow.next;//1+1*k
}
// 如果fast不为空,说明链表的长度是奇数个
// 123 4 321 如果奇数,slow指的是中间那个,要从下一个开始反转;
// 123 321 如果偶数个,从slow开始就行
if(fast != null){
slow = slow.next;
}
slow = reverse(slow); // 从slow开始反转
while(slow != null){
if(slow.val != head.val)
return false;
slow = slow.next;
head = head.next;
}
return true;
}
// 反转链表
public ListNode reverse(ListNode head){
ListNode pre = null;
while(head != null){
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
学到的点:
1、如何通过快慢指针找到链表的中点
2、复习链表反转