力扣——两个链表的数字和

题目

    public static ListNode addTwoNumbersTwo(ListNode l1, ListNode l2) {

        ListNode t1 = l1;
        ListNode t2 = l2;

        ListNode one = new ListNode(0);
        ListNode target = one;
        int x = 0;//第1个链表的每个位置的值
        int y = 0; //第2个链表的每个位置的值
        int jinWei = 0;//0表示不进位,1表示进位
        int sum = 0;//表示两个链表的相同位置的相加后的值
        //注意判断的是它们只要任意一个不为空就继续,即使其中一个为空,把它置零就好了
        while (t1 != null || t2 != null) {
            if (t1 != null) {
                x = t1.val;
            } else {
                x = 0;
            }
            if (t2 != null) {
                y = t2.val;
            } else {
                y = 0;
            }
            sum = jinWei + x + y;
            jinWei = sum / 10;//如果大于10进位
            //新建一个Node节点表示target下一个元素
            target.next = new ListNode(sum % 10);
            System.out.println(sum % 10);
            if (t1 != null) {
                t1 = t1.next;
            }
            if (t2 != null) {
                t2 = t2.next;
            }
            target = target.next;
        }
        // 加到最后一位
        if (jinWei > 0) {
            target.next = new ListNode(jinWei);

        }
        return one.next;

    }

其中有一个理论,注意看下面的one和target最后会变为什么?

   ListNode one = new ListNode(0);
        ListNode target = one;
        target.next=new ListNode(2);
        target =target.next;
        target.next=new ListNode(3);
        target =target.next;
        target.next=new ListNode(4);
        target =target.next;
我们发现我们其实没有动过one,但是one却有值,而且是2,3,4都有,相反,target只剩最后一个值
one: 0,2,3,4
target : 4
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值