力扣234題(回文鍊錶)

2022-06-20 18:24:09 字數 1584 閱讀 6882

一、遞迴法,空間複雜度太大,不採用,

但是要會遞迴是如何進行的,噁心死我了

看不懂官方的快慢指標

將鍊錶後半部分反轉,然後將前半部分和後半部分進行比較。

比較完後將鍊錶恢復原樣

1、通過「雙指標技巧」中的快、慢指標來找到鍊錶的中點

慢指標一次走一步,快指標一次走兩步

慢指標最後在的地方就是鍊錶的中點

2、反轉後半部分鍊錶時

分奇偶情況。

如果fast沒有指向null,說明鍊錶長度是奇數,slow還要再往前一步

3、從slow開始反轉後面的鍊錶

返回反轉之後的頭結點

4、開始比較

class

solution:

def ispalindrome(self, head: listnode) ->bool:

if head is

none:

return

true

#找到slow並反轉後半部分鍊錶

second_half_start =self.reverse_list(self.end_of_first_half(head))

#判斷是否回文

result =true

first_position =head

second_position =second_half_start

while result and second_position is

notnone:

if first_position.val !=second_position.val:

result =false

first_position =first_position.next

second_position =second_position.next

#還原鍊錶並返回結果

self.reverse_list(second_half_start)

return

result

defend_of_first_half(self, head):

fast =head

slow =head

while fast is

not none and fast.next is

notnone:

fast =fast.next.next

slow =slow.next

if fast is

notnone:

return

slow.next

else

:

return

slow

defreverse_list(self, head):

previous =none

current =head

while current is

notnone:

next_node =current.next

current.next =previous

previous =current

current =next_node

return previous

力扣 234 回文鍊錶

1.快慢指標 找中點 注意奇偶 分開反轉後半鏈 比較 以後半鏈為主 class solution listnode cur low next 後半鏈當前指標 listnode pre null 用於反轉 摘掉結點 頭插法 low next null 斷鏈 low head 重置low 反轉 whil...

力扣 234 回文鍊錶

一 題目描述 請判斷乙個鍊錶是否為回文鍊錶。示例 1 輸入 1 2 輸出 false 示例 2 輸入 1 2 2 1 輸出 true 二 解題思路 1 先找到鍊錶的中間節點。2 對中間結點的後半部分進行逆置。3 從鍊錶的頭節點和逆置之後的新頭節點進行比較即可。注意 鍊錶的長度為奇數個節點和偶數個節點...

力扣(LeetCode)234 回文鍊錶

請判斷乙個鍊錶是否為回文鍊錶。示例 1 輸入 1 2 輸出 false 示例 2 輸入 1 2 2 1 輸出 true 高階 你能否用 o n 時間複雜度和 o 1 空間複雜度解決此題?思路 尋找中間結點,然後將後半部分鍊錶倒置,後半部分鍊錶長度是小於或等於原鍊錶的,所以根據後半部分鍊錶來確定對比迴...