forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0002-add-two-numbers.dart
More file actions
41 lines (38 loc) · 882 Bytes
/
0002-add-two-numbers.dart
File metadata and controls
41 lines (38 loc) · 882 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode? next;
* ListNode([this.val = 0, this.next]);
* }
*/
class Solution {
ListNode? addTwoNumbers(ListNode? l1, ListNode? l2) {
ListNode ?listnode;
int carry = 0;
while (l1 != null || l2 != null) {
int val = (l1?.val ?? 0) + (l2?.val ?? 0) + carry;
l1 = l1?.next;
l2 = l2?.next;
if (val > 9){
val = val - 10;
carry = 1;
} else {
carry = 0;
}
if (listnode != null)
listnode = ListNode(val, listnode);
else
listnode = ListNode(val);
}
if (carry != 0){
listnode = ListNode(carry, listnode);
}
var list;
while (listnode != null) {
list = ListNode(listnode.val, list);;
listnode = listnode?.next;
}
return list;
}
}