public class Leetcode_0002_AddTwoNumbers {
public static class ListNode {
int val
ListNode next
ListNode() {
}
ListNode(int val) {
this.val = val
}
ListNode(int val, ListNode next) {
this.val = val
this.next = next
}
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// 参数清洗
if (l1 == null && l2 == null) {
return null
}
if (l1 == null) {
return l2
}
if (l2 == null) {
return l1
}
// 新的头
ListNode preHead = new ListNode(-1)
// 进位 cp
int cp = 0
int val1 = 0
int val2 = 0
int cur = 0
ListNode curNode = preHead
while (l1 != null || l2 != null) {
val1 = l1 == null ? 0 : l1.val
val2 = l2 == null ? 0 : l2.val
cur = val1 + val2 + cp
curNode.next = new ListNode(cur % 10)
cp = cur / 10
l1 = l1 == null ? l1 : l1.next
l2 = l2 == null ? l2 : l2.next
curNode = curNode.next
}
// 处理进位 cp
if (cp > 0) {
curNode.next = new ListNode(cp)
}
return preHead.next
}
public static void main(String[] args) {
var l1 = new ListNode(1)
l1.next = new ListNode(9)
l1.next.next = new ListNode(9)
var l2 = new ListNode(1)
l2.next = new ListNode(9)
// 2-> 8 -> 0 -> 1
var head = addTwoNumbers(l1, l2)
while (head != null) {
System.out.print(head.val + "-> ")
head = head.next
}
}
}