Hello everyone, I am Strolling Coding. I am sorting out the 2022 LeetCode high-frequency algorithm interview questions recently. I feel good, you can like and bookmark it. At the same time, any additional feedback is welcome. This article was first published on the public account: stroll coding

image.png

The title comes from Question No. 2 on LeetCode: Adding Two Numbers. The difficulty of the question is Medium, and the current pass rate is 33.9%.

Topic description

Give two non-empty linked lists representing two non-negative integers. Among them, their respective digits are stored in reverse order , and each of their nodes can only store one digit.

If, we add these two numbers together, a new linked list is returned to represent their sum.

You can assume that neither number starts with 0, except for the number 0.

<font color=#FF000 >Title difficulty: ★★</font>

Example 1:

 输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.

Example 2:

 输入:l1 = [0], l2 = [0]
输出:[0]

Example 3:

 输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]

hint:

 每个链表中的节点数在范围 [1, 100] 内
0 <= Node.val <= 9
题目数据保证列表表示的数字不含前导零

Topic Analysis

Set up a variable representing the carry carried , create a new linked list, process the two input linked lists from the beginning to the back at the same time, add each two, and add the result after carried The value is added to the back of the new list as a new node.

Code

tips: The following codes are different solutions implemented by using Go code. At the end of the article, you can see the implementation in C++, C, Java, and Python.

1. Loop through and sum up

 /**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    var carry int
    resultList := &ListNode{}
    current := resultList

    for{
        if l1 == nil && l2 == nil && carry == 0{
            break
        }

        if l1 != nil{
            carry += (*l1).Val
            l1 = l1.Next
        }

        if l2 != nil{
            carry += (*l2).Val
            l2 = l2.Next
        }

        node := ListNode{}

        if carry <= 9{
            node = ListNode{
                Val: carry,
            }
            carry = 0
        }else{
            node = ListNode{
                Val: carry - 10,
            }
            carry = 1
        }

        current.Next = &node
        current = &node
    }

    return resultList.Next
}

Results of the

2. Improvement method, <font color=#FF000>If the lengths of l1 and l2 are very different, you can directly use the back part of the long linked list to avoid repeating the new Node node</font>.

 func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    var carry int
    resultList := &ListNode{}
    current := resultList

    for{
        node := ListNode{}
        if l1 == nil && l2 == nil && carry == 0{
            break
        }

        if l1 != nil{
            if l2 == nil && carry == 0{
                current.Next = l1
                break
            }else{
                carry += (*l1).Val
                l1 = l1.Next
            }
        }

        if l2 != nil{
            if l1 == nil && carry == 0{
                current.Next = l2
                break
            }else{
                carry += (*l2).Val
                l2 = l2.Next
            }
        }

        if carry <= 9{
            node = ListNode{
                Val: carry,
            }
            carry = 0
        }else{
            node = ListNode{
                Val: carry - 10,
            }
            carry = 1
        }

        current.Next = &node
        current = &node
    }

    return resultList.Next
}

Results of the

3. Method 3 uses the recursive method to sum two arrays, which will not be discussed in detail here.

Other language versions

C++

 /// 时间复杂度: O(n)
/// 空间复杂度: O(n)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

        ListNode *p1 = l1, *p2 = l2;
        ListNode *dummyHead = new ListNode(-1);
        ListNode* cur = dummyHead;
        int carried = 0;
        while(p1 || p2 ){
            int a = p1 ? p1->val : 0;
            int b = p2 ? p2->val : 0;
            cur->next = new ListNode((a + b + carried) % 10);
            carried = (a + b + carried) / 10;

            cur = cur->next;
            p1 = p1 ? p1->next : NULL;
            p2 = p2 ? p2->next : NULL;
        }

        cur->next = carried ? new ListNode(1) : NULL;
        ListNode* ret = dummyHead->next;
        delete dummyHead;
        return ret;
    }
};

Results of the

Java

 class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode cur = dummyHead;
        int carry = 0;

        while(l1 != null || l2 != null)
        {
            int sum = carry;
            if(l1 != null)
            {
                sum += l1.val;
                l1 = l1.next;
            }
            if(l2 != null)
            {
                sum += l2.val;
                l2 = l2.next;
            }
            // 创建新节点
            carry = sum / 10;
            cur.next = new ListNode(sum % 10);
            cur = cur.next;
    
        }
        if (carry > 0) {
            cur.next = new ListNode(carry);
        }
        return dummyHead.next;
    }
}

Results of the

Python

 class Solution(object):
    def addTwoNumbers(self, l1, l2):
        res=ListNode(0)
        head=res
        carry=0
        while l1 or l2 or carry!=0:
            sum=carry
            if l1:
                sum+=l1.val
                l1=l1.next
            if l2:
                sum+=l2.val
                l2=l2.next
            # set value
            if sum<=9:
                res.val=sum
                carry=0
            else:
                res.val=sum%10
                carry=sum//10
            # creat new node
            if l1 or l2 or carry!=0:
                res.next=ListNode(0)
                res=res.next
        return head

Results of the

Comparison of running effects of several languages


漫步coding
685 声望30 粉丝