Skip to content

Commit 2baf088

Browse files
authored
Update 2-add-two-numbers.js
1 parent 130ee4c commit 2baf088

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

2-add-two-numbers.js

+41
Original file line numberDiff line numberDiff line change
@@ -117,4 +117,45 @@ const addTwoNumbers = function(l1, l2) {
117117
return dummy.next
118118
};
119119

120+
// another
121+
122+
/**
123+
* Definition for singly-linked list.
124+
* function ListNode(val, next) {
125+
* this.val = (val===undefined ? 0 : val)
126+
* this.next = (next===undefined ? null : next)
127+
* }
128+
*/
129+
/**
130+
* @param {ListNode} l1
131+
* @param {ListNode} l2
132+
* @return {ListNode}
133+
*/
134+
const addTwoNumbers = function(l1, l2) {
135+
const dummy = new ListNode(null)
136+
let cur = dummy, carry = 0
137+
138+
while(l1 || l2) {
139+
let v = 0
140+
if(l1 && l2) {
141+
v = l1.val + l2.val + carry
142+
l1 = l1.next
143+
l2 = l2.next
144+
} else {
145+
const node = l1 || l2
146+
v = node.val + carry
147+
if(l1) l1 = l1.next
148+
if(l2) l2 = l2.next
149+
}
150+
151+
cur.next = new ListNode(v % 10)
152+
cur = cur.next
153+
if(v >= 10) carry = 1
154+
else carry = 0
155+
}
156+
157+
if(carry) cur.next = new ListNode(1)
158+
159+
return dummy.next
160+
};
120161

0 commit comments

Comments
 (0)