/**
* 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) {
//1.寻找中间节点
ListNode mid = findMidNode(head);
//2.反转后半部分链表
mid = reverseList(mid);
ListNode temp = head;
//3.比较值
while(temp != null){
if(temp.val != mid.val) {
return false;
}
temp = temp.next;
mid = mid.next;
}
return true;
}
//寻找中间节点
public ListNode findMidNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
if(fast != null)
return slow.next;
return slow;
}
//反转链表
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while(cur != null) {
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
leetcode回文链表,这样写为什么会出现空指针异常?