链接:https://leetcode.com/problems/add-two-numbers/
原题:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 0 -> 8
分析:
这道题实际上就是倒叙的链表,最终算出和,并以链接的形式呈现。
还是循环,但要注意可能有进1位 以及 两个数字长度不同的问题
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode l1tmp = l1;
ListNode l2tmp = l2;
int add1 = 0;
while (true) {
int l1num = l1tmp.val;
int l2num = l2tmp ==null?0:l2tmp.val;
int value = l1num + l2num + add1;
add1 = value / 10;
value = value % 10;
l1tmp.val = value;
if (l1tmp.next == null) {
if((l2tmp!=null && l2tmp.next!=null)|| add1!=0) {
l1tmp.next = new ListNode(0);
} else {
break;
}
}
l1tmp = l1tmp.next;
l2tmp = l2tmp == null?null:l2tmp.next;
}
return l1;
}
代码效率没有很高,待优化