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