坚持第49天啦,加油加油!!!
题目
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
示例 1:
输入:head = [1,2,2,1]
输出:true
示例 2:
输入:head = [1,2]
输出:false
提示:
链表中节点数目在范围[1, 105] 内
0 <= Node.val <= 9
代码
/**
* 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) {
ListNode prenode=new ListNode(-1);
prenode.next=head;
ListNode fast=prenode;
ListNode slow=prenode;
while(fast!=null&&fast.next!=null)
{
fast=fast.next.next;
slow=slow.next;
}
ListNode newhead=slow.next;
slow.next=null;
ListNode cur=newhead;
ListNode pre=null;
while(cur!=null)
{
ListNode temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
}
newhead=pre;
while(newhead!=null)
{
//System.out.println("newhead:"+newhead.val+"head:"+head.val);
if(newhead.val!=head.val)
{
return false;
}
else {
newhead=newhead.next;
head=head.next;
}
}
return true;
}
}
反思
发现对于快慢指针找中间的问题,最初的快慢指针是指向头结点还是虚拟头结点,导致找到的中间结点是不一样的,根据具体情况解决。