題目說要時間複雜度O(n),空間複雜度O(1)的解法,我沒做出來。。。
我的解法就是簡單的把問題轉化爲迴文數列:速度倒是很快,就是空間佔用很高使用了一個result保存所有值
# 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:
result = []
while head is not None:
result.append(head.val)
head = head.next
return result == result[::-1]