First, understand the topic

2. Add the two numbers

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.

Example:

Input: l1 = [2, 3], l2 =,6,4 [5] output:,0,8 [7] : 342 + 465 = 807.Copy the code

Ii. Solution analysis

(1) How to solve the problem

  • Primary school mathematics;
  • Simulate adding operations.

(2) Steps to solve the problem

  • Create an empty linked list;
  • Iterate over the two lists to be added and simulate the addition operation;
  • Appends the units digit to the new list, leaving the tens digit for the next digit to add.

Three, code implementation

Based on the above solution, we will use JS to implement this problem. The specific implementation code is as follows:

/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
/ * * *@param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}* //** * l1 and l2 are linked nodes * leetcode inserts them directly * in actual development, we need to write an insert method to insert the corresponding values */let addTwoNumbers = function(l1, l2){
    const l3 = new ListNode(0);
    let p1 = l1;
    let p2 = l2;
    let p3 = l3;
    let carry = 0;  // carry indicates carry
    while(p1 || p2){
        const v1 = p1 ? p1.val : null;
        const v2 = p2 ? p2.val : null;
        const val = v1 + v2 + carry;
        carry = Math.floor(val / 10);
        p3.next = new ListNode(val % 10);
        if(p1){
            p1 = p1.next;
        }
        if(p2){
            p2 = p2.next;
        }
        p3 = p3.next;
    }
    if(carry){
        p3.next = new ListNode(carry);
    }
    return l3.next;
}
Copy the code

The above is about the addition of two numbers solution, DO not know whether it is helpful to small friends?

We’ll see you next time at 👋👋👋