234.回文链表
1.题目
2.我的解决方案
想不出来空间复杂度为 O ( 1 ) 的 情 况 O(1)的情况 O(1)的情况
3.官方的解决方案
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
# 想不到空间复杂度为常数级的情况
# 使用双指针法:将链表的后半部分进行反转
# 1.避免空链表
if not head:
return True
# 2.使用快慢指针法找到链表的中间部分
slow = head
fast = head
while fast.next and fast.next.next: # 注意合适的判定条件,让slow处于中间的结点
slow = slow.next # 步长为1
fast = fast.next.next # 步长为2
# 当循环停止时,slow处于链表中间位置,fast在链表尾部
# 为了统计奇数和偶数的操作,将slow对应结点后面的第一个结点作为后半段开始
# 3. 从slow开始将链表反转
pre = None
cur = slow.next
slow.next = None # 从中间部分断开
while cur:
next_node = cur.next # 保存下一个结点位置
cur.next = pre # 反转
pre = cur # 前指针移动
cur = next_node # cur移动
cur1 = head
cur2 = pre # 后半段头节点应该是pre
# 4.比较回文
while cur1 and cur2:
if cur1.val != cur2.val:
return False
cur1 = cur1.next
cur2 = cur2.next
return True
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( 1 ) O(1) O(1)