Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
Latest commit
76 lines (66 loc) · 1.78 KB
/
Copy pathSolution.java
File metadata and controls
76 lines (66 loc) · 1.78 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package_2;
// remove the line of `package xxx.xxx.xxx.xxx;` when you commit it
/**
* @author relish
* @since 2018/04/02
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
classSolution {
publicListNodeaddTwoNumbers(ListNodel1, ListNodel2) {
ListNodefirstNode = null;
ListNodeprev = null;
intco = 0;
while (l1 != null || l2 != null) {
intval1 = l1 == null ? 0 : l1.val;
intval2 = l2 == null ? 0 : l2.val;
intval = val1 + val2 + co;
if (val >= 10) {
val %= 10;
co = 1;
} else {
co = 0;
}
if (firstNode == null) {
firstNode = newListNode(val);
prev = firstNode;
} else {
ListNodenewNode = newListNode(val);
prev.next = newNode;
prev = newNode;
}
l1 = l1 == null ? null : l1.next;
l2 = l2 == null ? null : l2.next;
}
if (co == 1) {
prev.next = newListNode(1);
}
returnfirstNode;
}
publicstaticvoidmain(String[] args) {
ListNodel1 = newListNode(2);
l1.next = newListNode(4);
l1.next.next = newListNode(3);
ListNodel2 = newListNode(5);
l2.next = newListNode(6);
l2.next.next = newListNode(4);
ListNodelistNode = newSolution().addTwoNumbers(l1, l2);
while (listNode != null) {
System.out.print(listNode.val + " ");
listNode = listNode.next;
}
}
}
classListNode {
intval;
ListNodenext;
ListNode(intx) {
val = x;
}
}