给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// Initialize variables
ListNode result = new ListNode(0); // Head node
ListNode prevNode = result;
int carry = 0;
while (l1 != null || l2 != null) {
int x = (l1 != null) ? l1.val : 0;
int y = (l2 != null) ? l2.val : 0;
int sum = x + y + carry;
// Update carry
if (sum > 9) {
carry = 1;
sum %= 10;
} else {
carry = 0;
}
// Update the linked list
ListNode currentNode = new ListNode(sum);
prevNode.next = currentNode;
prevNode = currentNode;
// Move to the next nodes of l1 and l2
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
// Check if there is any carry left
if (carry != 0) {
prevNode.next = new ListNode(carry);
}
// Return the resulting list
return result.next;
}
}