- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path002_Add_Two_Numbers.java
More file actions
Latest commit
30 lines (30 loc) · 799 Bytes
/
Copy path002_Add_Two_Numbers.java
File metadata and controls
30 lines (30 loc) · 799 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
publicclassSolution {
// example in leetcode book
publicListNodeaddTwoNumbers(ListNodel1, ListNodel2) {
ListNodedummyHead = newListNode(0);
ListNodep = l1, q= l2, curr = dummyHead;
intcarry = 0;
while (p != null || q!= null) {
intx = (p != null) ? p.val : 0;
inty = (q != null) ? q.val : 0;
intdigit = carry + x + y;
carry = digit / 10;
curr.next = newListNode(digit % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = newListNode(carry);
}
returndummyHead.next;
}
}