234. 回文链表(java)
个人理解:
1.先找到链表的中间节点,将链表分为前后两部分
方法:设置快慢指针,初始都指向头节点,慢指针每次走一步,快指针每次走两步。循环结束条件为:快指针后两个元素不为空,此时慢指针指的就是前半部分链表的最后一个节点。将该节点返回。
2.对后半部分链表进行翻转
传入上一步返回结果的next,如leftEnd.next。 对后半部分链表进行翻转。翻转后返回后半部分链表的头节点,也就是pre指针。
3.对两部分链表分别从头开始比较
class Solution{public boolean isPalindrome(ListNode head){// 1.找到中间节点,翻转后面部分的链表if(head==null){return false; }ListNode leftEnd=middleList(head); //找到左边部分链表的结束位置ListNode rightStart=reverseList(leftEnd.next); // 翻转后边部分的链表,返回头节点//开始比较两部分链表,判断回文ListNode a=head;ListNode b=rightStart;while(b!=null){if(a.val!=b.val){return false;}a=a.next;b=b.next;}return true;} public ListNode middleList(ListNode head){// 利用快慢指针找中间节点ListNode slow=head;ListNode fast=head;// 移动快慢指针while(fast.next!=null&&fast.next.next!=null){slow=slow.next;fast=fast.next.next;}return slow;}//翻转链表public ListNode reverseList(ListNode head){ListNode cur=head; //初始cur指针指向头节点,pre指针指向空ListNode pre=null;while(cur!=null){ // 翻转和移动pre,cur 先移动pre,否则cur会被覆盖ListNode tmp=cur.next;cur.next=pre;pre=cur;cur=tmp;}return pre;}
}