给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode current1=l1;
ListNode current2=l2;
Stack<Integer> resultStack = new Stack();
int nextAddNum = 0;
do {
Integer currentNum1 = null == current1 ?0:current1.val;
Integer currentNum2 = null == current2 ?0:current2.val;
Integer currentAddResult = currentNum1+currentNum2+nextAddNum;
if (currentAddResult>=10) {
resultStack.push(currentAddResult%10);
nextAddNum=1;
} else {
resultStack.push(currentAddResult);
nextAddNum=0;
}
current1 = current1.next;
current2 = current2.next;;
}
while (null != current1 || null != current2) ;
if (nextAddNum==1) {
resultStack.push(nextAddNum);
}
ListNode result = null;
ListNode currentResult=new ListNode();
for (Integer integer : resultStack) {
if (result == null) {
result = new ListNode(integer);
currentResult = result;
} else {
currentResult.next = new ListNode(integer);
currentResult = currentResult.next;
}
}
return result;
}
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;
}
}