2. Add Two Numbers

2. Add Two Numbers

英文题目

You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

题目大意

常考题目,链表相加。
有两个链表,链表节点分别代表数字的位数,求两个链表的和。例如:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
代表的是:
342 + 465 = 807.

解题思路

Solution1

考察基本的线性表,按照十进制,把余数留到下一次个节点相加的时候就好了。
时间复杂度是o(max(m, n)).
非递归解法的时候要注意边界,只要有余数就要执行。
递归解法,可以只考虑两个节点相加,要进行两步,首先是节点相加,然后是相加的结果和余数相加。

type ListNode struct {
    Val  int
    Next *ListNode
}

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    node := &ListNode{Val: 0, Next: nil}
    n1, n2, tmp := l1, l2, node
    sum := 0

    for n1 != nil || n2 != nil {
        sum /= 10
        if n1 != nil {
            sum += n1.Val
            n1 = n1.Next

        }
        if n2 != nil {
            sum += n2.Val
            n2 = n2.Next
        }
        tmp.Next = &ListNode{Val: sum % 10}
        tmp = tmp.Next
    }
    if sum/10 != 0 {
        tmp.Next = &ListNode{Val: 1}
    }
    return node.Next
}

Complexity Analysis

  • 时间复杂度:O(n2)。2次百里循环所以时间复杂度是O(n2)。
  • 空间复杂度:O(1)

结语

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:awesome-golang-leetcode


  Reprint please specify: KYLE LIU 2. Add Two Numbers

  TOC