参考代码:
class Solution {
public boolean isPalindrome(ListNode head) {
if (head.next == null){
return true;
}
ListNode slow = head;
ListNode fast = head.next;
while (fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
ListNode cur = slow.next;
slow.next = null;
ListNode pre=null;
while(cur!=null){
ListNode temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
}
while(head != null && pre != null){
if (head.val != pre.val){
return false;
}
head=head.next;
pre=pre.next;
}
return true;
}
}
大致思路:找到中点,分成两半,然后反转,进行对比。
实现:通过快慢指针找到中点,ListNode cur = slow.next;slow.next = null;,分成两个链表;
将前一节链表反转:
while(cur!=null){
ListNode temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
}
具体实现过程:
反转后的与未反转的另一半进行对比,一旦中间出现不一样的就return false。