链式A+B

有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。

给定两个链表ListNode* A,ListNode* B,请返回A+B的结果(ListNode*)。

测试样例:
{1,2,3},{3,2,1}
返回:{4,4,4}

解析:需要考虑到进位,两个链表长度不同,和进位如果发生在链表尾部时需要多加一位的情况。

代码:

    public ListNode plusAB(ListNode a, ListNode b) {
        ListNode aTemp = a;
        ListNode bTemp = b;
        int push = 0;
        ListNode ret = null;
        ListNode temp = null;
        while (aTemp != null && bTemp != null) {
            if (ret == null) {
                ret = new ListNode(0);
                temp = ret;
            } else {
                temp.next = new ListNode(0);
                temp = temp.next;
            }
            temp.val = (aTemp.val + bTemp.val + push) % 10;
            push = (aTemp.val + bTemp.val + push) >= 10 ? 1 : 0;
            aTemp = aTemp.next;
            bTemp = bTemp.next;
        }
        while (aTemp != null) {
            if (ret == null) {
                ret = new ListNode(0);
                temp = ret;
            } else {
                temp.next = new ListNode(0);
                temp = temp.next;
            }
            temp.val = (aTemp.val + push) % 10;
            push = (aTemp.val + push) >= 10 ? 1 : 0;
            aTemp = aTemp.next;
        }
        while (bTemp != null) {
            if (ret == null) {
                ret = new ListNode(0);
                temp = ret;
            } else {
                temp.next = new ListNode(0);
                temp = temp.next;
            }
            temp.val = (bTemp.val + push) % 10;
            push = (bTemp.val + push) >= 10 ? 1 : 0;
            bTemp = bTemp.next;
        }
        if (push != 0) {
            temp.next = new ListNode(push);
        }
        temp = ret;
        while (temp != null) {
            temp = temp.next;
        }
        return ret;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值