cci-Q2.4 链表的值相加

原文:

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

EXAMPLE

Input: (3 –> 1 –> 5), (5 –> 9 –> 2)

Output: 8 –> 0 –> 8

译文:

你有两个由单链表表示的数。每个结点代表其中的一位数字。数字的存储是逆序的, 也就是说个位位于链表的表头。写一函数使这两个数相加并返回结果,结果也由链表表示。

例子:(3 –> 1 –> 5), (5 –> 9 –> 2)

输入:8 –> 0 –> 8

使用递归,如果anode和bnode不同时为空,则new一个新的morenode,morenode.data=anode.data+bnode.data+carry(上一次相加的进位)。

 public static void main(String args[]) {
        // a = 815
        int a[] = {5, 1, 8,};
        // b = 3186
        int b[] = {6, 8, 1, 3};
        LinkedListNode aNode = arrToList(a);
        LinkedListNode bNode = arrToList(b);

        //output aNode: 518
        printList(aNode);
        //output bNode 6813
        printList(bNode);

        LinkedListNode result = add(aNode, bNode, 0);

        //output result 1004
        printList(result);

    }

    public static void printList(LinkedListNode a) {
        LinkedListNode tmp = a;
        while (tmp != null) {
            System.out.println(tmp.data);
            tmp = tmp.next;
        };
        System.out.println("");
    }

    public static LinkedListNode arrToList(int[] a) {
        LinkedListNode node = null;
        LinkedListNode tmp = null;
        for (int i = 0; i < a.length; i++) {
            LinkedListNode next = new LinkedListNode(a[i]);
            if (i == 0) {
                node = tmp = next;
                continue;
            }
            tmp.next = next;
            tmp = next;
        }
        return node;
    }

    public static LinkedListNode add(LinkedListNode a, LinkedListNode b, int carry) {
        if (a == null && b == null) {
            return null;
        }

        LinkedListNode result = new LinkedListNode(carry);
        int value = carry;
        if (a != null) {
            value += a.data;
        }
        if (b != null) {
            value += b.data;
        }

        result.data = value % 10;

        LinkedListNode more = add(a == null ? null : a.next, b == null ? null : b.next, value > 9 ? 1 : 0);

        result.next = more;
        return result;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值