原题
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
Reference Answer
思路分析
这道题要是想简单做,也很省事,直接遍历用 list 依次存入node.value
,然后使用再反向遍历该list与原链表的值做一一对比,完全相同,完整“回文”要求,输出 True
; 存在不相同元素,则不满足,输出 False
。
此时时间复杂度、空间复杂度均为 O(n)。
优化版:
既然题中提出,争取使用 O(n) time and O(1) space,这里借鉴之前做过的在 O(1) space下反转链表的思想,即:
- 遍历得到链表长度;
- 以中间节点做切分,分为前后两段;
- 对后半段进行 O(1) 空间复杂度的反转;
- 再对前半段与反转后的后半段进行值的一一比较,都相同,满足“回文”条件,输出
True
,否则,输出False
。
Code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return True
node = head
length = 0
while node:
length += 1
node = node.next
middle = length / 2 # maybe decimal
left_length = 0
left = right = head
while left_length <= middle:
temp = left
left = left.next
left_length += 1
if length % 2 == 0:
right = temp
else:
right = temp.next
right_head = self.reverseList(right)
node = right_head
while node:
if node.val != head.val:
return False
head = head.next
node = node.next
return True
def reverseList(self, right):
if not right:
return
root = right
end = root
right = right.next
while right:
temp = right
right = right.next
temp.next = root
root =temp
end.next = None
return root