請判斷一個鏈表是否爲迴文鏈表。數組
示例 1:app
輸入: 1->2 輸出: false
示例 2:指針
輸入: 1->2->2->1 輸出: true
進階:
你可否用 O(n) 時間複雜度和 O(1) 空間複雜度解決此題?code
兩種方法:it
經過代碼以下:io
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from math import * class Solution: # # 改成數組:時間複雜度O(n),空間複雜度O(n) # def isPalindrome(self, head: ListNode) -> bool: # l = [] # while head: # l.append(head.val) # head = head.next # return l == l[::-1] # 指針法:時間複雜度O(n),空間複雜度O(1)。找到中點,反轉中點以後的鏈表,再比較 def isPalindrome(self, head: ListNode) -> bool: if not head or not head.next: return True # 找到中點,快指針走的路程是慢的兩倍,快指針結束慢指針恰好在中間 f = s = head while f: s = s.next f = f.next.next if f.next else f.next # 反轉中點以後的鏈表,1->2->0->2->1 ————》 1->2->0<-2<-1 c, p = s, None while c: n = c.next c.next = p p = c c = n # 相對比較 while p: if head.val != p.val: return False head = head.next p = p.next return True