classSolution: defreverseList(self, head: ListNode) -> ListNode: pre = None cur = head while cur: temp = cur.next cur.next = pre pre = cur cur = temp return pre
*另外可以用递归的方式反转链表:
classSolution: defreverseList(self, head: ListNode) -> ListNode: if head isNoneor head.nextisNone: return head
p = self.reverseList(head.next) head.next.next = head head.next = None return p
classSolution: defdeleteDuplicates(self, head: ListNode) -> ListNode: tag = head cur = head while cur: if tag.val == cur.val: tag.next = cur.next else: tag = cur cur = cur.next
classSolution: defaddTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: stack1, stack2 = [], [] cur = l1 while cur: stack1.append(cur.val) cur = cur.next cur = l2 while cur: stack2.append(cur.val) cur = cur.next
carry = 0 ret = None while stack1 or stack2 or carry != 0: a = 0ifnot stack1 else stack1.pop() b = 0ifnot stack2 else stack2.pop() curnode = ListNode((a + b + carry) % 10) carry = (a + b + carry) // 10
classSolution: defaddTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: a, b = l1, l2 tag = 0#短的(需要补0)的链表 dif = 0#两个链表的长度差 #完成补0 while a or b: tag = 1ifnot a else2 ifnot a ornot b: dif += 1 if a: a = a.next if b: b = b.next
if tag == 1: while dif > 0: t = ListNode(0) t.next = l1 l1 = t dif -= 1 elif tag == 2: while dif > 0: t = ListNode(0) t.next = l2 l2 = t dif -= 1
#反转两条链表 pre = None while l1: t = l1.next l1.next = pre pre = l1 l1 = t l1 = pre pre = None while l2: t = l2.next l2.next = pre pre = l2 l2 = t l2 = pre
#加法计算 ret = None carry = 0 while l1 or l2 or carry != 0: a = 0ifnot l1 else l1.val b = 0ifnot l2 else l2.val curnode = ListNode((a + b + carry) % 10) carry = (a + b + carry) // 10
classSolution: defisPalindrome(self, head: ListNode) -> bool: cur = head new_head = None while cur: t = ListNode(cur.val) t.next = new_head new_head = t cur = cur.next
while head: if head.val != new_head.val: returnFalse head = head.next new_head = new_head.next
# 如果传来空链表,则直接返回长度为k的空list ifnot root: for i inrange(k): ret.append(None) return ret
# 计算链表的长度 cur = root length = 0 while cur: length += 1 cur = cur.next
# amount中每个值代表将链表分割后,每段的长度。具体的计算过程请看本题的第一张图。 amount = [] x = length // k y = length % k for i inrange(k): t = x if y > 0: x += 1 y -= 1 amount.append(x) x = t # 现在amount的值为[2, 2, 1]
pre = None l = amount.pop() for i inrange(l): pre = root root = root.next if l != 0: pre.next = None ret.append(temp_head) else: ret.append(None)
return ret
简化一下上个解法。
classSolution: defsplitListToParts(self, root: ListNode, k: int) -> List[ListNode]: cur = root for N inrange(1001): ifnot cur: break cur = cur.next width, remainder = divmod(N, k)
ans = [] cur = root for i inrange(k): head = write = ListNode(None) tag = 1if i < remainder else0 for j inrange(width + tag): write.next = write = ListNode(cur.val) if cur: cur = cur.next ans.append(head.next) return ans