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
题意:求两个链表的和,注意链表是反向存储值的,所以如果遇到进位的时候向后进而不是向前
解题思路:首先遍历两个链表,需要注意的是最后一个结点如果有进位,需要new一个结点。直接用 l1 来存放结果。如果l2比l1长,则还得在l1后加入后面的l2.。然后l1挪到l2的位置,再判断l1的每个位是否需要进位。如果l2比l1短,则直接判断l1的每个位是否需要进位。
/**
* 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 l2;
}
if (l2 == null && l1 != null) {
return l1;
}
if (l2 == null && l1 == null) {
return null;
}
//指向l1的前一个节点
ListNode preNodeL1 = new ListNode(0);
preNodeL1.next = l1;
//保存结果
ListNode res = l1;
//进位标志
int flag = 0;
while (l1 != null && l2 != null) {
int sum = l1.val + l2.val + flag;
flag = sum / 10;
l1.val = sum % 10;
preNodeL1 = l1;
l1 = l1.next;
l2 = l2.next;
}
//如果l2长度比l1长,在l1之后再加上l2,并把l1挪到l2所在位置
if(l2 != null) {
preNodeL1.next = l2;
l1 = l2;
}
//接下来判断l1所在位置是否需要进位
while (l1 != null) {
l1.val += flag;
flag = l1.val / 10;
l1.val = l1.val % 10;
preNodeL1 = l1;
l1 = l1.next;
}
if (flag > 0) {
ListNode tmpNode = new ListNode(1);
preNodeL1.next = tmpNode;
}
return res;
}
}