题目
给你一个单链表的头节点 head
,请你判断该链表是否为回文链表。如果是,返回 true
;否则,返回 false
。
代码
/**
* 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==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;
}
}
反思
很巧妙,先找中间元素,然后反转链表。
发现对于快慢指针找中间的问题,最初的快慢指针是指向头结点还是虚拟头结点,导致找到的中间结点是不一样的,根据具体情况解决。