正好复习一下链表
Question
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse orderand 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.
Code provided:
1 | /** |
Solution
source: leetcode
En
Before starting summing up two lists, create a new linked list to store the summed up value. Given and , starting with the head of and . Each digit is in the range of , so it is possible that summing two digits may result in a value that is greater than 9, therefore require digits to represent. Hence, extra digit is needed during each iteration to carry the overflowing value.
CN
代码中已经提供了和,因此所需要的步骤就是创建一个新的空的linked list。从头开始迭代和,并将相加的数值存入到新的linked list之中。值得注意的事情就是,每个数字的区间是,因此,当两位数字相加的时候就可能会出现十位数的可能,也就因此需要额外的变量保存十位数的数字。
Code
Java
1 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { |
Python3
1 | def addTwoNumbers(self, l1, l2): |
Complexity Analysis
Time Complexity:
Space Complexity: