leetcode 234.回文链表(python)
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
class Solution(object):
def isPalindrome(self, head):
# 快慢指针, 翻转后面的链表, 然后对比前后部分是否相同
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
node = None
while slow:
nxt = slow.next
slow.next = node
node = slow
slow = nxt
while node:
if node.val != head.val:
return False
node = node.next
head = head.next
return True