阅读 88

算法题-Leetcode 两数相加

前言

LeetCode 两数相加

思路

这个思路没啥好讲的,主要看代码吧。写了两个,一个递归,一个非递归。 递归的那个逻辑很显而易见,但是new了很多结点。而非递归的则最多只new一个 Node,不过逻辑稍多。

代码

递归



public static class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    return addTwoNumbe(l1,l2,0);
}
public ListNode addTwoNumbers2(ListNode l1, ListNode l2, int remain) {
    if (l1 == null && l2 == null) return remain != 0 ? new ListNode(remain, null) : null;
    if (l1 != null) {
        remain = l1.val + remain;
        l1 = l1.next;
    }
    if (l2 != null) {
        remain = l2.val + remain;
        l2 = l2.next;
    }
    return new ListNode(remain % 10, addTwoNumbers2(l1, l2, remain / 10));
}
复制代码

非递归

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    int a = 0;
    ListNode header = l1;
    ListNode cur = l1;
    while (l1 != null && l2 != null) {
        a = l1.val + l2.val + a;
        cur.val = a % 10;
        a = a / 10;
        l1 = l1.next;
        l2 = l2.next;
        cur.next = l1 != null ? l1 : l2;
        if (cur.next == null && a != 0) {
            cur.next = new ListNode(a, null);
            a = 0;
        }
        cur = cur.next;
    }
    while (cur != null && a != 0) {
        a = cur.val + a;
        cur.val = a % 10;
        a = a / 10;
        if (cur.next == null && a != 0) {
            cur.next = new ListNode(a, null);
            a = 0;
        }
        cur = cur.next;
    }
    return header;
}

复制代码
文章分类
代码人生
文章标签