【题目】

将两个用list存储的数字相加,返回相加后的值

 

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 contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

 

Example 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Example 2:

Input: l1 = [0], l2 = [0]
Output: [0]

Example 3:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]

 

【思路】

注意审题,输入输出都是倒序!!之前没看清题,还用stack遍历到顶端再返回………

倒序正常找next相加就行,几个易错点

  • 再巩固下指针地址等,tmp是全程处理的listnode,用ans指向tmp,最后返回的是ans
  • 又因为tmp的root节点初始化值为0,最后返回ans.next跳过(Q:那为什么不直接初始化为空 A:因为空指针不方便操作!)
  • 如果出现如下错误,多了个0,【7,0,5,0】

           

大概率因为写成了这样

为什么不能这么写,因为sum全局变量后,while判断的sum其实是上一轮的sum!!

那么我们思考sum>0的意义,是l1 l2均为null,但存在进位cnt的情况。

于是直接while循环外判断即可

        if(cnt>0)
            tmp.next=new ListNode(cnt);

 

【代码】

class Solution {
  public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int cnt=0;
        ListNode tmp=new ListNode(0);
        ListNode ans=tmp;
        while (l1!=null||l2!=null){
int sum=(l1==null?0:l1.val)+(l2==null?0:l2.val)+cnt; cnt=sum/10;
tmp.next
=new ListNode(sum%10); tmp=tmp.next;

//长度不等时
if(l1!=null) l1= l1.next; if(l2!=null) l2= l2.next; } if(cnt>0) tmp.next=new ListNode(cnt); return ans.next; } }

 

 posted on 2021-08-31 14:31  alau  阅读(26)  评论(0编辑  收藏  举报