File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change
1
+ // O(1) space
2
+ public class Solution {
3
+ public ListNode AddTwoNumbers ( ListNode l1 , ListNode l2 ) {
4
+ if ( l1 == null ) return l2 ;
5
+ if ( l2 == null ) return l1 ;
6
+ ListNode dummy = new ListNode ( 0 ) ;
7
+ ListNode head = dummy ;
8
+ int carry = 0 ;
9
+ int sum = 0 ;
10
+ while ( l1 != null && l2 != null ) {
11
+ head . next = l1 ;
12
+ head = head . next ;
13
+ sum = l1 . val + l2 . val + carry ;
14
+ head . val = sum % 10 ;
15
+ carry = sum / 10 ;
16
+ l1 = l1 . next ;
17
+ l2 = l2 . next ;
18
+ }
19
+ if ( l1 != null ) {
20
+ head . next = l1 ;
21
+ }
22
+ if ( l2 != null ) {
23
+ head . next = l2 ;
24
+ }
25
+
26
+ while ( head . next != null ) {
27
+ head = head . next ;
28
+ sum = head . val + carry ;
29
+ head . val = sum % 10 ;
30
+ carry = sum / 10 ;
31
+ if ( carry == 0 ) break ;
32
+ }
33
+ if ( carry != 0 ) {
34
+ head . next = new ListNode ( carry ) ;
35
+ }
36
+ return dummy . next ;
37
+ }
38
+ }
39
+
40
+ // O(m+n) space
41
+ public class Solution {
42
+ public ListNode AddTwoNumbers ( ListNode l1 , ListNode l2 ) {
43
+ if ( l1 == null ) return l2 ;
44
+ if ( l2 == null ) return l1 ;
45
+ ListNode dummy = new ListNode ( 0 ) { next = l1 } ;
46
+ ListNode cur = dummy ;
47
+ int carry = 0 ;
48
+ int sum = 0 ;
49
+ while ( l1 != null || l2 != null ) {
50
+ int x = ( l1 != null ) ? l1 . val : 0 ;
51
+ int y = ( l2 != null ) ? l2 . val : 0 ;
52
+ sum = x + y + carry ;
53
+ cur . next = new ListNode ( sum % 10 ) ;
54
+ carry = sum / 10 ;
55
+ if ( l1 != null ) l1 = l1 . next ;
56
+ if ( l2 != null ) l2 = l2 . next ;
57
+ cur = cur . next ;
58
+ }
59
+ if ( carry != 0 ) {
60
+ cur . next = new ListNode ( carry ) ;
61
+ }
62
+ return dummy . next ;
63
+ }
64
+ }
You can’t perform that action at this time.
0 commit comments