234.回文链表
- 给你一个单链表的头节点head,请你判断该链表是否为回文链表。如果是, 返回 true ; 否则, 返回false。
- 思路:
- 找到中间节点(快慢指针法)
- 反转后半部分的链表
- 比较前半部分和后半部分链表
class Solution(object):
def isPalindrome(self, head):
"""
:type head: Optional[ListNode]
:rtype: bool
"""
if not head or not head.next:
return True
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
prev = None
while slow:
next_node = slow.next
slow.next = prev
prev = slow
slow = next_node
left, right = head, prev
while right:
if left.val != right.val:
return False
left = left.next
right = right.next
return True
- 时间复杂度:O(n),其中 n 是链表的长度,总共遍历了三遍链表,n+n+n = 3n,时间复杂度忽略常数级故为O(n)
- 空间复杂度:O(1)