list两道2_445

2. Add Two Numbers

将两个链表相加,每个链表尾部是数字的最高位
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    int sum = 0;
    ListNode head = new ListNode(0);
    ListNode tail = head;
    while (l1 != null || l2 != null) {
        sum /= 10;
        if (l1 != null) {
            sum += l1.val;
            l1 = l1.next;
        }
        if (l2 != null) {
            sum += l2.val;
            l2 = l2.next;
        }

        tail.next = new ListNode(sum % 10);
        tail = tail.next;
    }

    if (sum / 10 != 0) {
        tail.next = new ListNode(1);
    }

    return head.next;
}

445. Add Two Numbers II

将两个链表相加,链表第一位是数字的最高位
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

有两种方法:使用stack或者递归

  1. 用stack就是分别储存两个链表的值,再取出来相加
  2. 用递归要首先知道两个链表的长度差值,然后长的链表先递归,直到剩下链表长度和短的相等后,两个链表一起递归
  3. 递归到最后一位时将两个链表相加,并返回进位值,不断向上层回溯最后得到解,下面是递归方法代码
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode c1 = l1, c2 = l2;
    int len1 = 0, len2 = 0;
    while (c1 != null) {
        len1++;
        c1 = c1.next;
    }
    while (c2 != null) {
        len2++;
        c2 = c2.next;
    }

    ListNode nl1 = null, nl2 = null;
    if (len1 >= len2) {
        nl1 = l1;
        nl2 = l2;
    } else {
        nl1 = l2;
        nl2 = l1;
    }

    ListNode head = new ListNode(0);
    int mark = addNode(nl1, nl2, Math.abs(len1 - len2), head);
    if (mark != 0) {
        ListNode temp = new ListNode(1);
        temp.next = head.next;
        head.next = temp;
    }
    return head.next;
}

public int addNode(ListNode l1, ListNode l2, int diff, ListNode head) {
    if (diff > 0) {
        int mark = addNode(l1.next, l2, diff - 1, head);
        int sum2 = mark + l1.val;
        mark = sum2 / 10;
        ListNode temp = new ListNode(sum2 % 10);
        temp.next = head.next;
        head.next = temp;
        return mark;
    }

    if (l1 == null && l2 == null)
        return 0;

    int mark = addNode(l1.next, l2.next, diff, head);

    int sum = l1.val + l2.val + mark;
    mark = sum / 10;
    ListNode temp = new ListNode(sum % 10);
    temp.next = head.next;
    head.next = temp;

    return mark;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值