给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
代码
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null)
return true;
ListNode node=new ListNode(-1);
node.next=head;
ListNode fast=node;
ListNode slow=node;
while(fast!=null&&fast.next!=null)
{
fast = fast.next.next;
slow = slow.next;
}
ListNode head2=slow.next;
slow.next=null;
//System.out.println("slow"+slow.val+"head2"+head2.val);
ListNode pre=null;
ListNode cur=head2;
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;
}
}
反思
很巧妙,先找中间元素,然后反转链表。



