生活随笔
收集整理的這篇文章主要介紹了
【LeetCode笔记】234. 回文链表(Java、快慢指针、链表)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
題目描述
- 寫這道題前最好把206.翻轉鏈表 寫了
- 有空間復雜度的話都好說,不管是新建鏈表、還是用字符串equals都好做。
思路 & 算法
快指針找終點,慢指針反轉前半個鏈表快指針回到慢指針的位置(中點,記得進行奇偶判斷)此刻,鏈表已經被分成兩條以slow、fast開始的鏈表,遍歷對比即可
class Solution {public boolean isPalindrome(ListNode head
) {ListNode fast
= head
, slow
= head
;ListNode temp
,pre
= null;while(fast
!= null && fast
.next
!= null){fast
= fast
.next
.next
;temp
= slow
.next
;slow
.next
= pre
;pre
= slow
;slow
= temp
;}fast
= fast
== null ? slow
: slow
.next
;slow
= pre
;while(slow
!= null){if(slow
.val
!= fast
.val
){return false;}slow
= slow
.next
;fast
= fast
.next
;}return true;}
}
class Solution {public boolean isPalindrome(ListNode head
) {if(head
.next
== null) {return true;}ListNode slow
= head
, fast
= head
;ListNode pre
= null;while(fast
!= null && fast
.next
!= null) {fast
= fast
.next
.next
;ListNode next
= slow
.next
;slow
.next
= pre
;pre
= slow
;slow
= next
;}if(fast
!= null) {slow
= slow
.next
;}while(pre
!= null) {if(pre
.val
!= slow
.val
) {return false;}pre
= pre
.next
;slow
= slow
.next
;}return true;}
}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的【LeetCode笔记】234. 回文链表(Java、快慢指针、链表)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。