add two numbers Solution

You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

1
2
3
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Solution

思路

这个题是一道使用链表进行整数加法运算的题。
需要考虑进位和两个链表长度不同的情况。
在最后需要对末尾进行特殊操作。即最后一位进位为1。

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int newValue = 0;
int nextNewValue = 0;
int num1,num2 = 0;
ListNode result = new ListNode(0);
ListNode temp = result;
while(l1 != null || l2 != null){
num1 = l1 != null ? l1.val:0;
num2 = l2 != null ? l2.val:0;
newValue = num1 + num2 + nextNewValue;
nextNewValue = 0;
if(newValue >=10){
newValue = newValue - 10;
nextNewValue ++;
}
//temp.val = newValue;
temp.next = new ListNode(newValue);
temp = temp.next;
if(l1 != null)
l1 = l1.next;
if(l2 != null)
l2 = l2.next;
}
if(nextNewValue == 1){
temp.next = new ListNode(1);
}
return result.next;
}
}