LeetCode系列之Add Two Numbers

问题描述

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

翻译一下:给两个单向非空链表所代表的非负整数,存储的时候会将他们逆置,你需要将它们加起来用链表输出
是不是有点难理解,还好它给了例子
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
总体思路:两个链表相加,需要考虑,
  1. 进位
  2. 两个链表长度不同、相同
  3. 1和2叠加到一起

重点

由于我是将第一条链表的基础上进行操作,所以涉及到链表1最后为null且需要进位的情况,这时候可不能仅仅将l1赋值为新节点(由于java的值传递),所以需要有辅助节点记录最后一个非null节点
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int temp = -1;
        int add = 0;

        /**这里用一个辅助节点的用意就在于,由于我们是拿1的空间做的新 链表,
        存在最后l1.next为null的情况,在处理进位的时候不能仅仅将l1被赋值为新节点(java的值传递),所以我们不能将希望全放在l1上,
        这就是pre节点的作用,记录最后一个非null节点**/
        ListNode pre = new ListNode(0);
        pre.next = l1;
        ListNode result = pre;
        while (l1 != null && l2 != null) {
            temp = l1.val + l2.val + add;
            add = temp / 10;
            temp = temp%10;
            l1.val = temp;
            pre = l1;
            l1 = l1.next;
            l2 = l2.next;

        }
        if (l1 == null && l2 != null) {//2比1长
            pre.next = l2;
            while (add != 0 && l2 != null) {
                temp = l2.val + add;
                l2.val = temp  % 10;
                add = temp / 10;
                pre = l2;
                l2 = l2.next;
            }
            if(add != 0){//2最后还有一个进位需要处理
                ListNode last = new ListNode(add);
                pre.next = last;
                last.next = null;
            }
            return result.next;
        }else if (l2 == null && l1 != null) {//1比2长
            while (add != 0 && l1 != null) {
                temp = l1.val + add;
                l1.val = temp % 10;
                add = temp / 10;
                pre = l1;
                l1 = l1.next;
            }
            if(add != 0){//1最后还有一个进位需要处理
                ListNode last = new ListNode(add);
                pre.next = last;
                last.next = null;
            }
            return result.next;
        }else if (l1 == null && l2 == null){
            if (add != 0) {
                ListNode last = new ListNode(add);
                pre.next = last;
                last.next = null;
                return result.next;
            }else {
                return result.next;
            }


        }
        return result.next;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值