错误解法一:正序查找的过程中,将前面的元素倒叙插入inverse链中,找到偶数中点时,对称查找。
java
/**
* 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) {
if(head.next == null){
// 只有一个元素
return true;
}
ListNode inverse=null, find=head;
while(find != null){
// 把find倒叙插入inverse中
ListNode temp=find.next;
find.next = inverse;
inverse = find;
find = temp;
while(find != null && inverse != null && find.val == inverse.val){
// 找到中点在find和find.next之间
find = find.next;
inverse = inverse.next;
}
}
if(find==null && inverse==null ){
return true;
}
return false;
}
}
错误原因:没有考虑奇数情况

解法一:将数据转存到列表中,用双指针比较。
java
/**
* 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) {
List<Integer> list = new ArrayList<>();
// 将所有数据放入list中
while(head!=null){
list.add(head.val);
head=head.next;
}
// 使用左右指针查找
int left=0,right=list.size()-1;
while(left<right){
if(list.get(left)!=list.get(right)){
return false;
}
right--;
left++;
}
return true;
}
}