2. Add Two Numbers
Last updated
Was this helpful?
Last updated
Was this helpful?
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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Example 2:
Example 3:
Constraints:
The number of nodes in each linked list is in the range [1, 100]
.
0 <= Node.val <= 9
It is guaranteed that the list represents a number that does not have leading zeros.
Linked List, Math
结果将存储在新链表上。首先创建新链表的头节点并用一个指针cur
指向它。初始化进位变量c
。进入循环,条件是l1
和l2
至少有一个不为空。如果l1
不为空,则将l1.Val
累加到cur.Val
并且l1
指向其下一个元素,l2
也一样。更新进位变量c = cur.Val / 10
,以及当前节点值cur.Val %= 10
。创建cur
的下一个节点并初始化其值为c
,并将cur
指向它。与此同时用另一个指针pre
维护cur
移动前的位置。退出循环后,如果cur.Val == 0
,则要通过pre.Next = nil
将cur
指向的节点移除。最后返回新链表头部节点指针。
We create a new list to store the sum of two input lists. We assign a pointer cur
to the head of the new list, and initialize a carry variable c
. Enter a loop which condition is either l1
or l2
is not null
. Then, if l1 is not null, add l1.Val
to cur.Val
and l1
points to its next node, so does l2
. Update the carry c = cur.Val / 10
, and the current value cur.Val %= 10
. We initialize a new node whose value is equal to c
and assign it to cur.Next
. Then we move cur
to this new next. Meanwhile, we use another pointer pre
to keep track of the position before cur
moving. After the loop, we have to check if cur.Val == 0
, if so we need to set pre.Next = nil
to purge the node that cur
points to. Return the head node of the new list in the end.
Time complexity:
Space complexity: