leetcode 2. Add Two Numbers

using java;ListNode单向链表相关

题目

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.

难度

medium(关键在于理解单向链表)

思路

  1. 输出也是一个链表,所以要有head指针;要在链表后面添加新的数据,所以要有tail指针
  2. 两数加法,考虑进位问题,先定义一个变量存储每位计算出来的值
  3. 循环什么时候停止?2个链表都为空并且进位为0的时候,得出while循环的条件
  4. 针对l1,l2不空的情况进行对应的相加和链表后移操作
  5. 处理进位
  6. 根据head是不是为空修改结果链表

代码

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head=null,tail=null;
        int curval=0;
        while(l1!=null||l2!=null||curval!=0){
            if(l1!=null){
                curval+=l1.val;
                l1=l1.next;
            }
            if(l2!=null){
                curval+=l2.val;
                l2=l2.next;
            }
            int outnum=curval%10;
            curval/=10;
            if(head==null){
                head=new ListNode(outnum);
                tail=head;
            }else{
                tail.next=new ListNode(outnum);
                tail=tail.next;
            }
        }
        return head;
    }
}

注意点

  • if(l1!=null) 和 if(l2!=null)不需要用else连接,因为这2句考虑都是不空,则加上数值并后移,如果为空,就不做任何操作
  • curval/10是进位,在下次加上
  • 画图,画图!链表类型的题画图思路清晰很多,head和tail都有实际意义
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值