def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: stack1 = [] stack2 = [] while l1: stack1.append(l1.val) l1 = l1.next while l2: stack2.append(l2.val) l2 = l2.next node = None carry = 0 while stack1 or stack2: x = stack1.pop() if stack1 else 0 y = stack2.pop() if stack2 else 0 val = x + y + carry carry = val // 10 n = val % 10 cur = ListNode(n) cur.next = node #!!!!!!!!!!!!!!!!!!尾插法 node = cur # 判断最高位是否有进位 if carry != 0: res = ListNode(carry) res.next = cur return res return cur
def addTwoNum(self, l1, l2): ans = ListNode(0) if not l1: return l2 if not l2: return l1 val = l1.val + l2.val ans = ListNode(val % 10) ans.next = self.addTwoNum(l1.next, l2.next) if val >= 10: ans.next = self.addTwoNum(ListNode(1), ans.next) return ans
def swapPairs(self, head: ListNode) -> ListNode: if not head or not head.next: return head cur = head.next head.next = self.swapPairs(cur.next) cur.next = head return cur
def Mundane(self, head): ans = ListNode(-1) ans.next = head pre = ans cur = ans.next while cur and cur.next: tmp = cur.next pre.next = tmp cur.next = tmp.next tmp.next = cur pre = cur cur = cur.next return ans.next