1. 原始题目
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
2. 题目理解
就上题而言很清楚了,两个非负整数相加,结果存在新链表中,注意的是:
1)进位,新建一个存放进位
2)两个链表长短不同,就是两个位数不同的整数。例如:999999+120
3. 解法
思路:两个链表按位依次向右滑动,不必反转链表,再相加,这时最直观最麻烦的方法。其实可以直接相加,比如123+269 = 492和“321+962 = 294”性质一样,就是进位的时候,要进到链表的后面去。所亦可以写出如下的代码:
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution: 8 def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 9 p = ListNode(0) 10 head = p # 保存最初的头结点,因为要返回头结点嘛 11 q = 0 # 保存商(商需要进位到下一位) 12 13 while(l1 and l2): # 当两者都不为空,依次向右滑动指针 14 q, r = (l1.val+l2.val+q)//10, (l1.val+l2.val+q)%10 # 分别保存商和余数 15 p.next = ListNode(r) # 余数放到当前结点,商还在q里面 16 p = p.next 17 l1 = l1.next 18 l2 = l2.next # 向右滑动 19 20 l = l1 or l2 # 若l1或者l2还有剩余,继续上述操作 21 while(l): 22 q, r = (l.val+q) // 10, (l.val+q) % 10 23 p.next = ListNode(r) 24 p = p.next 25 l = l.next 26 27 if q>0: # 若商大于0,需再开辟一个节点存放进位。例如 9+8 = 17 链表长为2,存放为7-1 28 p.next = ListNode(q) 29 30 return head.next
写完之后可能看到代码冗余很大,因为有许多部份重复了,虽然时间复杂度很小了,但是代码不够美观,将上面代码中三处判断整合到一起:即l1不为空,l2不为空,q不为0只要满足一个条件就新开辟结点存放数据:
1 class Solution: 2 def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 3 p = ListNode(0) 4 head = p 5 q = 0 6 7 while(l1 or l2 or q): # 满足之一即可 8 total = (l1.val if l1 else 0) + (l2.val if l2 else 0) + q 9 q = total // 10 10 r = total % 10 11 p.next = ListNode(r) 12 p = p.next 13 l1 = l1.next if l1 else l1 14 l2 = l2.next if l2 else l2 15 16 return head.next 17
效果是一样的:验证如下:
1 # 新建链表1 2 listnode1 = ListNode_handle(None) 3 s1 = [1,8,1,2,3,6] 4 for i in s1: 5 listnode1.add(i) 6 listnode1.print_node(listnode1.head) 7 8 # 新建链表2 9 listnode2 = ListNode_handle(None) 10 s2 = [9,4,6,3] 11 for i in s2: 12 listnode2.add(i) 13 listnode2.print_node(listnode2.head) 14 15 # 查看相加结结果 16 s = Solution() 17 head = s.addTwoNumbers(listnode1.head, listnode2.head) 18 listnode = ListNode_handle(None) 19 listnode.print_node(head)
1 8 1 2 3 6
9 4 6 3
0 3 8 5 3 6
还是,具体链表实现代码见博文。