class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null)return true;
ListNode thead = head;
ListNode mid = findMid(head);
mid = reverse(mid);
while(mid!=null&&thead!=null){
if(mid.val!=thead.val){
return false;
}
mid = mid.next;
thead = thead.next;
}
return true;
}
public ListNode findMid(ListNode head){
int i = 1;
ListNode temp = head;
while(temp.next!=null){
temp = temp.next;
i++;
}
temp = head;
for(int j=0;j<i/2;j++){
temp = temp.next;
}
return temp;
}
public ListNode reverse(ListNode head){
if(head.next==null){
return head;
}
ListNode mid = head.next;
if(head.next.next==null){
head.next.next = head;
head.next = null;
return mid;
}else{
ListNode forward = head.next.next;
ListNode back = head;
head.next = null;
while(forward!=null){
mid.next = back;
back = mid;
mid = forward;
forward = forward.next;
}
mid.next = back;
}
return mid;
}
}
本题的思路关键点为:
一、找到链表中点,然后断开链表,将后半部分翻转,随后进行比较。
二、对于链表操作时一定要注意对于传入的指针参数的操作,为了稳妥起见尽可能的在方法内创建一个新的指针指向传入的参数(比如head等),然后对新指针进行操作。
三、在while循环中,一定要在完成了自己需要的操作后对条件进行操作(自增,后移等)