The two together

You are given two non-empty linked lists representing two non-negative integers. Each digit is stored in reverse order, and only one digit can be stored per node.

You add the two numbers and return a linked list representing the sum in the same form.

You can assume that neither of these numbers will start with 0, except for the number 0.

Examples can be found on the LeetCode website.

Source: LeetCode link: leetcode-cn.com/problems/ad… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Solution 1: linked list traversal

Iterate over 2 linked lists, add values, record whether carry +1.

Note: When traversing to the last value of two linked lists, it is necessary to pay attention to whether there is a carry. If there is a carry, it is necessary to add a node.

public class Solution {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(0);
        ListNode cur = result;
        int addOne = 0;
        while(l1 ! =null|| l2 ! =null) {
            int sum = 0;
            sum += addOne;
            if(l1 ! =null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if(l2 ! =null) {
                sum += l2.val;
                l2 = l2.next;
            }
            addOne = sum / 10;
            cur.next = new ListNode(sum % 10);
            cur = cur.next;
        }
        if (addOne > 0) {
            cur.next = new ListNode(addOne);
        }

        return result.next;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);

        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);

        ListNode result = addTwoNumbers(l1, l2);
        System.out.println("result:");
        while(result ! =null) {
            System.out.print(result.val + ""); result = result.next; }}}class ListNode {

    int val;
    ListNode next;

    ListNode(intx) { val = x; }}Copy the code