Skip to content

Latest commit

 

History

History
36 lines (36 loc) · 1.13 KB

2.md

File metadata and controls

36 lines (36 loc) · 1.13 KB

#2. Add Two Numbers 题目链接

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 进位
        int inc = 0;
        // 先建立一个头结点,返回的时候返回头结点的next
        ListNode result = new ListNode(0);
        ListNode preHead = result;
        while (l1 != null || l2 != null) {
            int val1 = l1 == null ? 0 : l1.val;
            int val2 = l2 == null ? 0 : l2.val;
            int sum = val1 + val2 + inc;
            ListNode node;
            if (sum < 10) {
                node = new ListNode(sum);
                inc = 0;
            }
            else {
                node = new ListNode(sum % 10);
                inc = 1;
            }
            result.next = node;
            result = result.next;
            l1 = l1 == null ? l1 : l1.next;
            l2 = l2 == null ? l2 : l2.next;
        }
        // 如果全部结束后依然有进位,那么就新建一个结点加到最后
        if (inc == 1) {
            result.next = new ListNode(1);
        }
        return preHead.next;
    }
}