2. Add Two Numbers - jiejackyzhang/leetcode-note GitHub Wiki

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Linked List类题目

按顺序一个一个相加。这个题目有三个注意点:

  1. 两个链表长度不一定一样,而且可能会是空链表。只要有一个还未到end,就需创建一个node来存这一位的和值。若有一个已到end或者为空,就取0。
  2. 表头不能丢失,因为最后要返回结果链表的表头。这里可以创建一个dummyHeader, 最后返回dummyHeader.next即可,若两个链表都为空,返回为null。
  3. 进位。这里需要注意如果最后一位相加后还有进位,则需额外再创建一个node来存进位。
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;
        ListNode dummyHead = new ListNode(0);
        ListNode ans = dummyHead;
        while(l1 != null || l2 != null) {
            ans.next = new ListNode(0);
            ans = ans.next;
            int v1 = (l1 != null) ? l1.val : 0;
            int v2 = (l2 != null) ? l2.val : 0;
            ans.val = (v1 + v2 + carry) % 10;
            carry = (v1 + v2 + carry) / 10;
            if(l1 != null) {
                l1 = l1.next;
            }
            if(l2 != null) {
                l2 = l2.next;
            }
        }
        if(carry > 0) {
            ans.next = new ListNode(carry);
        }
        return dummyHead.next;
    }
}
⚠️ **GitHub.com Fallback** ⚠️