第一次解除到链表相关的题目,不会做,看了别人答案。
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: n=l1.val+l2.val l3=ListNode(n%10) l3.next=ListNode(n//10) p1=l1.next p2=l2.next p3=l3 while True: if p1 and p2: sum=p1.val+p2.val+p3.next.val p3.next.val=sum%10 p3.next.next=ListNode(sum//10) p1=p1.next p2=p2.next p3=p3.next elif p1 and not p2: sum=p1.val+p3.next.val p3.next.val=sum%10 p3.next.next=ListNode(sum//10) p1=p1.next p3=p3.next elif not p1 and p2: sum=p2.val+p3.next.val p3.next.val=sum%10 p3.next.next=ListNode(sum//10) p2=p2.next p3=p3.next else: if p3.next.val==0: p3.next=None break return l3
执行用时 :108 ms, 在所有 python3 提交中击败了32.62%的用户
内存消耗 :13.8 MB, 在所有 python3 提交中击败了5.06%的用户
不求其他,看懂就好。
执行用时为 52 ms 的范例 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 is None: return l2 if l2 is None: return l1 carry = 0 head = ListNode(0) node = head while l1 and l2: sum1 = l1.val + l2.val + carry carry = sum1//10 tmp = sum1%10 head.next = ListNode(tmp) head = head.next l1 = l1.next l2 = l2.next while l1: sum1 = l1.val+carry carry = sum1//10 tmp = sum1%10 head.next = ListNode(tmp) head = head.next l1 = l1.next while l2 : sum1 = l2.val + carry carry = sum1//10 tmp = sum1%10 head.next = ListNode(tmp) head = head.next l2 = l2.next if carry: head.next = ListNode(carry) head = head.next return node.next
——2019.10.23