1. 程式人生 > 實用技巧 >關於Linux自帶的python2.6.6升級到2.7.10版本步驟詳解

關於Linux自帶的python2.6.6升級到2.7.10版本步驟詳解

234. 迴文連結串列

Difficulty: 簡單

請判斷一個連結串列是否為迴文連結串列。

示例 1:

輸入: 1->2
輸出: false

示例 2:

輸入: 1->2->2->1
輸出: true

進階:
你能否用O(n) 時間複雜度和 O(1) 空間複雜度解決此題?

Solution

Language: ****

# Definition for singly-linked list.
# class ListNode:
#   def __init__(self, x):
#     self.val = x
#     self.next = None
​
class Solution:
  def isPalindrome(self, head: ListNode) -> bool:
    slow = fast = head
    while fast and fast.next:
      slow = slow.next
      fast = fast.next.next
    
    y = None
    while slow:
      nxt = slow.next
      slow.next = y
      y = slow
      slow = nxt
      
    while y:
      if y.val != head.val:
        return False
      head = head.next
      y = y.next
      
    return True