题解 | #两个链表生成相加链表#

两个链表生成相加链表

http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

1.首先把两个链表都反转
2.从头开始两个链表相加
3.反转相加后的链表

    public ListNode addInList2(ListNode head1, ListNode head2) {

        if (head1 == null) return head2;
        if (head2 == null) return head1;

        ListNode pre1 = null;
        ListNode next1;
        while (head1 != null) {
            next1 = head1.next;
            head1.next = pre1;
            pre1 = head1;
            head1 = next1;
        }

        ListNode pre2 = null;
        ListNode next2;
        while (head2 != null) {
            next2 = head2.next;
            head2.next = pre2;
            pre2 = head2;
            head2 = next2;
        }

        ListNode newHead = new ListNode(0);
        ListNode newTemp = newHead;

        int c = 0;
        while (pre1 != null || pre2 != null) {
            int a = 0;
            int b = 0;
            if (pre1 != null) {
                a = pre1.val;
                pre1 = pre1.next;
            }
            if (pre2 != null) {
                b = pre2.val;
                pre2 = pre2.next;
            }
            newTemp.next = new ListNode((a + b + c) % 10);
            newTemp = newTemp.next;
            c = (a + b + c) / 10;

        }

        if (c != 0) {
            newTemp.next = new ListNode(c);
        }
        ListNode head = newHead.next;
        ListNode pre = null;
        ListNode next = null;
        while (head != null) {

            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;

    }
全部评论

相关推荐

用户64975461947315:这不很正常吗,2个月开实习证明,这个薪资也还算合理,深圳Java好多150不包吃不包住呢,而且也提前和你说了没有转正机会,现在贼多牛马公司骗你说毕业转正,你辛辛苦苦干了半年拿到毕业证,后面和你说没hc了😂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务