[leetCode]34. 回文链表
快慢指针
思路:
1.将链表分为左右两部分
2.将右半部分翻转
3.使用两个指针判断是否是回文串
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null) return true;
// 1. 找到链表的中间节点
ListNode fast = head, slow = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode mid = slow;
ListNode rightCur = mid.next;
mid.next = null;
// 2. 反转右半部分的链表
ListNode prev = null;
while (rightCur != null) {
ListNode temp = rightCur.next;
rightCur.next = prev;
prev = rightCur;
rightCur = temp;
}
rightCur = prev;
ListNode leftCur = head;
while (leftCur != null && rightCur != null) {
if (leftCur.val != rightCur.val)
return false;
leftCur = leftCur.next;
rightCur = rightCur.next;
}
return true;
}
}