直接上题:
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
本题的大意是给了两个链表,需要按照类似进位加法的方法把两个链表对应的位加起来,得到一个新的链表。
大概的解题思路就是每一位对应相加然后再加上一位相加的进位。乍一看很简单,但是有很多边界条件要考虑到。首先如果两个当前节点都不为空的话,那么正常相加;如果其中有一个链表当前节点为空,则只把另外一个链表当前节点的值与上一位的进位相加;如果两个链表当前节点都为空,则再进一位,表示为一个节点。
Java code:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode aiter = l1, biter = l2, result = null,nowiter = null,temp;
int sum = 0,carry = 0,unit = 0;
while(aiter != null || biter != null)
{
if(aiter != null && biter != null)
{
sum = aiter.val + biter.val + carry;
carry = (sum > 9) ? 1 : 0;
unit = sum % 10;
aiter = aiter.next;
biter = biter.next;
}
else if(aiter == null)
{
sum = biter.val + carry;
carry = (sum > 9) ? 1 : 0;
unit = sum % 10;
biter = biter.next;
}
else if(biter == null)
{
sum = aiter.val + carry;
carry = (sum > 9) ? 1 : 0;
unit = sum % 10;
aiter = aiter.next;
}
if(result == null){
result = new ListNode(unit);
nowiter = result;
continue;
}
temp = new ListNode(unit);
nowiter.next = temp;
nowiter = temp;
}
if(carry > 0)
{
nowiter.next = new ListNode(carry);
}
return result;
}
补充解释一下:result == null
这个判断条件是加入第一个元素时的判断。
网友评论