You are given two linked lists representingtwo non-negative numbers. The digits are stored in reverse order and each oftheir nodes contain a single digit. Add the two numbers and return it as alinked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
解决该题的关键是要明确题意,实现加数和超过10之后,对应链表的位置保存的是个位数(temp % 10),而十位上的数字要以加数的形式和参加运算。尤其是在链表的最后,防止超10的情况发生,要判断这种情况。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null || l2 == null){
return null;
}
ListNode l3 = new ListNode(0);//创建l3要赋值
ListNode p1 = l1, p2 = l2, p3 = l3;
int temp = 0;
while(p1 != null || p2 != null){
if(p1 != null){
temp = temp + p1.val;
p1 = p1.next;
}
if(p2 != null){
temp = temp + p2.val;
p2 = p2.next;
}
p3.next = new ListNode(temp % 10);
p3 = p3.next;
temp = temp / 10;//记得将两数的和的十位加到l3的next的val中
}
if(temp == 1){//防止两个链表的最后结点相加的和大于10的情况
p3.next = new ListNode(1);
}
return l3.next;
}
}