请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
思路:先找到链表的中点,将中点及其以后的节点构成的链表利用反转链表的方法反转,然后依次和头节点比较值,如果都相等则代表是回文链表。
public boolean isPalindrome(ListNode head) {
if(head==null) return true;
if(head.next==null) return true;
ListNode fast=head;
ListNode low=head;
//利用快慢指针先找到链表的中点(1/2位置)
while(fast.next!=null&&fast.next.next!=null){
low=low.next;
fast=fast.next.next;
}
ListNode rehead=reverse(low.next);
//low.next=null;
while(rehead!=null&&head!=null){
if(rehead.val!=head.val){
return false;
}
rehead=rehead.next;
head=head.next;
}
return true;
}
public ListNode reverse(ListNode head){
if(head==null||head.next==null)
return head;
ListNode p1=head;
ListNode p2=head.next;
ListNode p3=head.next.next;
while(p2!=null){
p2.next=p1;
p1=p2;
p2=p3;
if(p3!=null){
p3=p3.next;
}
head.next=null;
}
return p1;
}