1. 问题描述:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
2. 思路分析:
① 首先是要读懂题目的意思,可以知道题目主要是求解出从左到右两个链表对应位置相加的结果,所以来说还是比较容易理解的,我们在循环中遍历两个链表,当两个链表有一个不为空的时候那么就执行循环,因为有可能出现这样的情况,比如9->9 + 1这种,所以需要两个链表都为空的时候才算处理完成,使用一个ListNode类型变量来表示当前即将要生成节点的上一个节点,使用这个变量的话连接元素会比较方便
② 可以使用一个变量来记录上一次的进位情况,然后在遍历链表的时候将两个链表对应位置的元素相加,同时更新进位变量的值,假如有一个链表为空了那么只更新另外一个链表与其进位的情况即可,最后判断一下进位是否为1,假如为1那么最后需要新建一个节点因为之前是进位了,需要将其连接起来,整个过程还是比较好理解的
③ 除了上面新建节点的话,还可以对其进行优化,只需要在原来的基础上修改链表的值从而可以不新建链表的节点,使用一个ListNode来记录前驱节点这样在一个链表为空的时候才好将pre的next指针域连接到另外一个链表上(两个链表有长短),然后在循环中更新另外一个链表的值与进位情况最后处理一下最后的进位即可
3. 代码如下:
class Solution{
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
if (l1 == null && l2 == null) return null;
if (l1 == null && l2 != null) return l2;
if (l1 != null && l2 == null) return l1;
ListNode pre = null;
ListNode head = null;
while (l1 != null || l2 != null){
/*即将要插入的节点*/
ListNode newNode;
if(l1 != null && l2 != null){
int curVal = l1.val + l2.val + carry;
carry = curVal / 10;
newNode = new ListNode(curVal % 10);
if (pre == null){
pre = newNode;
head = newNode;
}
else {
pre.next = newNode;
pre = newNode;
}
l1 = l1.next;
l2 = l2.next;
}
else if (l1 != null){
int curVal = l1.val + carry;
carry = curVal / 10;
newNode = new ListNode(curVal % 10);
if (pre == null) {
pre = newNode;
head = newNode;
}
else {
pre.next = newNode;
pre = newNode;
l1 = l1.next;
}
}else if (l2 != null){
int curVal = l2.val + carry;
carry = curVal / 10;
newNode = new ListNode(curVal % 10);
if (pre == null) {
pre = newNode;
head = newNode;
}
else {
pre.next = newNode;
pre = newNode;
l2 = l2.next;
}
}
}
if (carry == 1){
ListNode last = new ListNode(1);
pre.next = last;
}
return head;
}
}
优化代码:
class Solution{
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
if (l1 == null && l2 == null) return null;
if (l1 == null && l2 != null) return l2;
if (l1 != null && l2 == null) return l1;
ListNode pre = null, head = l1;
int curVal = 0;
while (l1 != null && l2 != null){
curVal = l1.val + l2.val + carry;
l1.val = curVal % 10;
carry = curVal / 10;
/*pre指针是为了避免l1比较短的情况*/
pre = l1;
l1 = l1.next;
l2 = l2.next;
}
while (l1 != null){
curVal = l1.val + carry;
l1.val = curVal % 10;;
carry = curVal / 10;
pre = l1;
l1 = l1.next;
}
if (l1 == null && l2 != null) pre.next = l2;
while (l2 != null){
curVal = l2.val + carry;
l2.val = curVal % 10;
carry = curVal / 10;
pre = l2;
l2 = l2.next;
}
if (carry == 1) {
ListNode last = new ListNode(1);
pre.next = last;
}
return head;
}
}