1、源代碼
class Solution {public boolean isPalindrome(ListNode head) {ListNode fast=head,slow=head; //快慢指針都在頭結點//快指針走2步,慢指針走一步。//雙數快指針最后是null,單數快指針下一位是nullwhile(fast!=null && fast.next!=null){fast=fast.next.next;slow=slow.next;}//移動之后,如果是奇數。此時slow在中位數,要向下移動一位if(fast!=null){slow=slow.next;}slow=reverse(slow);//反轉鏈表fast=head;//反轉之后快指針回到頭結點//對值進行比較while(slow!=null){if(fast.val!=slow.val){return false;}fast=fast.next;slow=slow.next;}return true;}/*反轉鏈表*/public ListNode reverse(ListNode curr){ListNode pre=null;while(curr!=null){ListNode next=curr.next;curr.next=pre;pre=curr;curr=next;}return pre;}
}
2、解析
1、題目
2、思路
我們把整個鏈表看成鏡像,因此我們只需要把左右進行對比,這樣就會出現一個奇偶數問題,因此判斷方法采用快慢指針
快指針一次走2步,慢指針一次走一步,當快指針走到null代表為偶數,快指針的next是null代表為奇數,因此得到以下代碼
while(fast!=null && fast.next!=null){fast=fast.next.next;slow=slow.next;
}
移動之后,如果是奇數。此時slow在中位數,要向下移動一位,因為中位數是誰都無所謂
if(fast!=null){slow=slow.next;
}
然后就需要把后半段鏈表進行反轉,此時要把快指針放到頭結點
slow=reverse(slow);//反轉鏈表
fast=head;//反轉之后快指針回到頭結點
反轉鏈表代碼:
public ListNode reverse(ListNode curr){ListNode pre=null;//這個為curr的前一個節點while(curr!=null){ListNode next=curr.next; //保存當前指針的下一個curr.next=pre; //把curr的next變成前一個(反轉核心)pre=curr; //把pre移動到currcurr=next;//把curr移動到next}return pre;
}
然后一一進行值對比,如果對不上直接false
while(slow!=null){if(fast.val!=slow.val){return false;}fast=fast.next;slow=slow.next;
}
return true;