请判断一个链表是否为回文链表。数组
示例 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