- 快慢指针找到一半
- 链表逆转
- 判断两链表是否相等
可以记忆一下快慢指针的板子,以head开头,slow.next就是以一半无论奇偶
import java.util.*;
public class Solution {
public boolean isPail (ListNode head) {
// 快慢指针找到一半
if(head == null)return false;
ListNode fast,slow,pre,p;
fast = slow = head;
while(fast.next!=null&&fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
//slow.next就是一半,然后链表逆转
slow = slow.next;
fast = slow;
pre = null;
while(fast!=null){
ListNode t = fast.next;
fast.next = pre;
pre = fast;
fast = t;
}
//判断两链表是否相等
while(pre!=null){
if(pre.val != head.val)return false;
pre = pre.next;
head = head.next;
}
return true;
}
}