只用單鏈表的方式判斷一個鏈表是否為回文鏈表
思路
-
尋找鏈表的中點:使用快慢指針的方法,快指針每次移動兩步,慢指針每次移動一步。當快指針到達鏈表末尾時,慢指針正好位于鏈表的中間。
-
反轉后半部分鏈表:從中點開始反轉鏈表的后半部分。
-
比較前半部分和反轉后的后半部分:逐一比較兩個部分的節點值,如果所有對應的節點值都相同,則鏈表是回文的。
-
(可選)恢復鏈表的原始結構:將反轉的后半部分再反轉回來,以恢復原鏈表結構。
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def isPalindrome(head: ListNode) -> bool: if head is None or head.next is None: return True # Step 1: Find the end of the first half first_half_end = end_of_first_half(head) # Step 2: Reverse the second half second_half_start = reverse_list(first_half_end.next) # Step 3: Compare the first half and the reversed second half p1 = head p2 = second_half_start result = True while result and p2 is not None: if p1.val != p2.val: result = False p1 = p1.next p2 = p2.next # Step 4: Restore the list (optional) first_half_end.next = reverse_list(second_half_start) return result def end_of_first_half(head: ListNode) -> ListNode: fast = head slow = head # Move fast by 2 steps and slow by 1 step until fast reaches the end while fast.next is not None and fast.next.next is not None: fast = fast.next.next slow = slow.next return slow def reverse_list(head: ListNode) -> ListNode: previous = None current = head while current is not None: next_node = current.next current.next = previous previous = current current = next_node return previous

浙公網安備 33010602011771號