Leetcode234. 回文链表
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
O(n) 时间复杂度和 O(1) 空间复杂度代码:
思路先快慢指针,利用慢指针找到中点,再对后半段反转,然后比较数值是否一样
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
low,fast = head,head
first = head
flag = 1
if not head:
return True
while fast.next != None:
#low指向中点
fast = fast.next
low = low.next
if fast.next != None:
fast = fast.next
flag = 1
#设立flag判断是奇数个还是偶数个
else:
flag = 0
break
if flag:
#奇数个节点则从中点后面一个节点开始反转
cur = low.next
low = cur
else:
cur = low
pre = None
while cur:
#反转后半段链表
nex = cur.next
cur.next = pre
pre = cur
cur = nex
re = 1
while pre and re:
#对比数值判断是否是回文
if pre.val != first.val:
re = 0
break
else:
pre = pre.next
first = first.next
return (True if re == 1 else False)
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list