生活随笔
收集整理的這篇文章主要介紹了
【LeetCode笔记】234. 回文链表(Java、快慢指针、链表)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
題目描述
- 寫這道題前最好把206.翻轉(zhuǎn)鏈表 寫了
- 有空間復(fù)雜度的話都好說,不管是新建鏈表、還是用字符串equals都好做。
思路 & 算法
快指針找終點(diǎn),慢指針反轉(zhuǎn)前半個(gè)鏈表快指針回到慢指針的位置(中點(diǎn),記得進(jìn)行奇偶判斷)此刻,鏈表已經(jīng)被分成兩條以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;}
}
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)
總結(jié)
以上是生活随笔為你收集整理的【LeetCode笔记】234. 回文链表(Java、快慢指针、链表)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。