# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defreverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: # 时间 On,空间 O1 # 这个写法下,pre会是原链表视角下反转部分的最后一个,cur在下一段第一个 pre, cur = None, head while cur: nxt = cur.next cur.next = pre pre = cur cur = nxt return pre
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defreverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: # 时间On,空间O1 # 重点是p0的更新需要注意,要更新为反转段原来的第一个位置,也就是反转后的最后一个位置 l = 0 p0 = head while p0: l += 1 p0 = p0.next c = l // k # print(c, l) dummy = ListNode(next = head) p0 = dummy for _ inrange(c): pre = p0.next cur = pre.next for i inrange(k-1): nxt = cur.next cur.next = pre pre = cur cur = nxt nextp0 = p0.next nextp0.next = cur p0.next = pre p0 = nextp0 return dummy.next
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next defreverseList(l): pre, cur = None, l while cur: nxt = cur.next cur.next = pre pre = cur cur = nxt return pre
classSolution: defaddTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: # 时间On,空间On,不过如果直接在l1或者l2上加数字,空间就O1了 l1 = reverseList(l1) l2 = reverseList(l2) ans = ListNode() cur = ans over = False while l1 or l2 or over: cur.next = ListNode(0, None) cur = cur.next if l1: cur.val += l1.val l1 = l1.next if l2: cur.val += l2.val l2 = l2.next
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next defreverseList(l): pre, cur = None, l while cur: nxt = cur.next cur.next = pre pre = cur cur = nxt return pre
classSolution: defdoubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]: # 时间On,空间On,不过如果直接在源链表上操作数字,空间就O1了 # 不过由于本题不会连续进位,所以其实另一种方法只考虑值大于4的节点前面操作这种更简单快速 head = reverseList(head) ans = ListNode() carry = False
while head or carry: cur = ListNode(0, ans.next) if head: cur.val += head.val * 2 head = head.next
if carry: carry = False cur.val += 1 if cur.val >= 10: cur.val -= 10 carry = True ans.next = cur