topic:
Two non-empty linked lists are given to represent two non-negative integers. Among them, their respective digits are stored in reverse order, and each node can only store one digit.
If we add these two numbers together, a new linked list will be returned to represent their sum.
You can assume that none of these numbers start with 0 except for the number 0.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Reason: 342 + 465 = 807
Code:
class Solution2 {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x; }
}
public static ListNode addNUmbers(ListNode l1,ListNode l2){
ListNode dummyHead = new ListNode(0);
ListNode p =l1; ListNode q = l2;ListNode curr = dummyHead;
int carry = 0;
while(p!= null || q != null || carry != 0){
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
return dummyHead.next;
}
}
Precautions:
1 The singly linked list can only be searched from the beginning.
2 Inverse numbers can also be added directly when adding. Add each digit and then directly carry it. Set the carry to carry, and enter the next iteration.
3 Need to consider the null pointer exception problem
4 If it is converted to an integer, it will compile and overflow.
5 Nothing is added at the beginning, so the carry must be 0