https://leetcode.com/problems/add-two-numbers/
Medium
问题描述: 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:
1 2 3 Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
题目分析及代码: LeetCode上的第二条题目,一道与链表操作相关的题目,两个链表,将对应位置上的数相加,超过十则进位,输出最终得到的链表。
思路1:
由于链表保存的顺序就是从低位到高位,因此我们直接遍历两个列表,按题目描述那样,对应位置相加,只需要注意最后一位相加需要进位的情况,例如(5) + (5)
,在遍历完成后需要对这种情况做额外处理,使得最终输出为0->1
而不是0
。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution : def addTwoNumbers (self, l1: ListNode, l2: ListNode ) -> ListNode: res = point = ListNode(0 ) extra = 0 while l1 != None or l2 != None : l1_ele = l1.val if l1 != None else 0 l2_ele = l2.val if l2 != None else 0 sum = l1_ele + l2_ele + extra extra = 1 if sum >= 10 else 0 point.next = ListNode(int (sum %10 )) point = point.next if l1 != None : l1 = l1.next if l2 != None : l2 = l2.next if extra == 1 : point.next = ListNode(1 ) return res.next
思路2:
可以通过递归来减少空间复杂度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Solution : def addTwoNumbers (self, l1: ListNode, l2: ListNode ) -> ListNode: if l1 != None and l2 != None : return elif (l1 and l2) == None : return l1 or l2 else : if l1.val + l2.val < 10 : res = ListNode(l1.val + l2.val) res.next = self.addTwoNumbers(l1.next , l2.next ) else : res = ListNode(l1.val + l2.val - 10 ) res.next = self.addTwoNumbers(l1.next , self.addTwoNumbers(l2.next , ListNode(1 ))) return res