题目:
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。
如果是,返回 true ;否则,返回 false 。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6597bd37cb6780f27b630ce612112eff.png)
输入:head = [1,2,2,1]
输出:true
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c198252abfe401d0163a0aa091b00a7a.png)
输入:head = [1,2]
输出:false
提示:
链表中节点数目在范围[1, 105] 内
0 <= Node.val <= 9
思考:
快指针走到末尾,慢指针刚好到中间。其中慢指针将前半部分反转。然后比较
pre temp 用于将前半段反转
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) return true;
ListNode slow = head;
ListNode fast = head;
ListNode pre = head;
ListNode prepre = null;
while (fast != null && fast.next != null) {
pre = slow;
slow = slow.next;
fast = fast.next.next;
pre.next = prepre;
prepre = pre;
}
if(fast != null) slow = slow.next;
while(pre != null && slow != null) {
if(pre.val != slow.val) {
return false;
}
pre = pre.next;
slow = slow.next;
}
return true;
}
}
LC