思路:
1.链表一分为二,快慢指针,slow和fast,fast不为空时,说明是元素为奇数个,slow再次指向下一个节点
fast为空,说明元素是偶数个,slow就是后半节点的头节点
2.比较两个链表元素值是否相等极客
3.注意,在快慢指针while循环中,为什么一定要先fast = fast.next.next放前面?放后面会fast.next为空指针。注意啊。因为slow刚开始代表的是头节点。先反转slow节点后,slow也是指向头节点,fast节点也是指向head节点,那可不fast.next.next就是空指针了。
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
public boolean isPail (ListNode head) {
// write code here
if(head == null || head.next == null ){
return true;
}
//快慢指针
ListNode slow = head;
ListNode fast = head;
ListNode pre = null;
// 4 3 2 1 2 3 4
//4 3 3 4
while(fast != null && fast.next != null){
fast = fast.next.next;
ListNode next = slow.next;
slow.next = pre;
pre = slow;
slow = next;
//fast = fast.next.next;
}
//4 3 2 3 4
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;
}
}