File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * public class ListNode {
4
+ * int val;
5
+ * ListNode next;
6
+ * ListNode() {}
7
+ * ListNode(int val) { this.val = val; }
8
+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9
+ * }
10
+ */
11
+
12
+ //Space: O(1)
13
+ //Time: O(max(len(l1), len(l2))
14
+ class Solution {
15
+ public ListNode addTwoNumbers (ListNode l1 , ListNode l2 ) {
16
+
17
+ ListNode dummy = new ListNode (0 );
18
+
19
+ ListNode sol = dummy ;
20
+
21
+ int carry = 0 ;
22
+
23
+ while (l1 != null || l2 != null ) {
24
+
25
+ int curr = 0 ;
26
+ if (l1 != null ) curr += l1 .val ;
27
+ if (l2 != null ) curr += l2 .val ;
28
+ curr += carry ;
29
+
30
+ sol .next = new ListNode (curr % 10 );
31
+ carry = curr / 10 ;
32
+
33
+ sol = sol .next ;
34
+ if (l1 != null ) l1 = l1 .next ;
35
+ if (l2 != null ) l2 = l2 .next ;
36
+
37
+ }
38
+
39
+ if (carry > 0 ) {
40
+ sol .next = new ListNode (carry );
41
+ }
42
+
43
+ return dummy .next ;
44
+
45
+ }
46
+ }
You can’t perform that action at this time.
0 commit comments