java-双向链表大数相加

直接上代码

/**
     * @Description 两个双向链表大数相加
     * @Author zhushengjie
     * @Date 2020/1/6 17:40
     **/
    @Test
    public void addLinkedListTest() {

        List integerList = Stream.of(5, 6, 7, 8, 9).collect(Collectors.toList());
        List integerList2 = Stream.of(9, 8 , 7, 6, 5, 4).collect(Collectors.toList());

        LinkedList a = new LinkedList<>(integerList);
        LinkedList b = new LinkedList<>(integerList2);
        System.out.println(a);
        System.out.println(b);

        if (!a.isEmpty() && !b.isEmpty()) {

            do {
                if (a.size() < b.size())
                    a.addFirst(0);
                else
                    b.addFirst(0);
            } while (a.size() != b.size());

            int ten = 0;
            if (a.size() == b.size()) {
                for (int i = 0; i < a.size(); i++) {
                    // 获取第一个双向链表最后的值
                    Integer integer = a.pollLast();
                    // 获取第二个双向链表最后的值
                    Integer integer2 = b.pollLast();

                    int total = integer + integer2;
                    if (ten != 0) {
                        total += ten;
                        ten = 0;
                    }
                    if (total >= 10) {
                        ten++;
                        total = total%10;
                    }
                    a.addFirst(total);

                }
            }
            // 判断最后的十位数是否为空
            if (ten != 0) {
                a.addFirst(ten);
            }

            System.out.println(a);
        }

    }

你可能感兴趣的:(java-双向链表大数相加)