# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defmiddleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: # 时间On,空间O1 # 当慢指针指向中间节点时,若链表长度奇数,则快指针指向最后一个,若为偶数则置空 # dummy = ListNode(0, head) # 如果要中间偏前的就从dummy出发 l, r = head, head while r and r.next: l = l.next r = r.next.next return l
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defhasCycle(self, head: Optional[ListNode]) -> bool: # 时间On,环内应该还有点,不过也和n有关,空间O1 l, r = head, head while r and r.next: l = l.next r = r.next.next if l == r: returnTrue returnFalse
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defdetectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: # 核心就是理解从slow=a+b,fast=a+b+k*(b+c),推到a=c+(k-1)(b+c) # 也就是slow从相遇点出发,和head一起在环入口相遇 # 时间On,空间O1 slow, fast = head, head while fast and fast.next: fast = fast.next.next slow = slow.next if fast == slow: # 必定有环 while slow != head: slow = slow.next head = head.next return slow returnNone
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defreorderList(self, head: Optional[ListNode]) -> None: """ Do not return anything, modify head in-place instead. """ # 时间On,空间O1 l, r = head, head # 先找到中间偏右的点 while r and r.next: l = l.next r = r.next.next pre, cur = None, l # 将右侧反转 while cur: nxt = cur.next cur.next = pre pre = cur cur = nxt
l = head r = pre # print("pre", pre) while r: # 左右指针重排 nxt = l.next nxt2 = r.next
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defisPalindrome(self, head: Optional[ListNode]) -> bool: # 一次遍历链表,反转后半段,再遍历一半链表,无额外存储空间 # 时间On,空间O1 l, r = head, head while r and r.next: r = r.next.next l = l.next
pre, cur = None, l while cur: nxt = cur.next cur.next = pre pre = cur cur = nxt while pre: if pre.val != head.val: returnFalse pre, head = pre.next, head.next returnTrue
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next defgetMid(head): slow, fast = head, head while fast and fast.next: fast = fast.next.next slow = slow.next return slow
defreverseList(head): pre, cur = None, head while cur: nxt = cur.next cur.next = pre pre = cur cur = nxt return pre
classSolution: defpairSum(self, head: Optional[ListNode]) -> int: # 时间:取中点遍历了一边,反转遍历一半,找孪生和遍历一半,On # 空间:没有额外变量,O1 mid = getMid(head) r = reverseList(mid) ans = 0 while r: cur = head.val + r.val