LeetCode-445. Add Two Numbers II

问题描述

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example :

1
2
Input: l1 = [7,2,4,3], l2 = [5,6,4]
Output: [7,8,0,7]

Constraints:

  • The number of nodes in each linked list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.

解答

方法一:反转链表

先将两个链表反转,然后从前往后逐个节点相加,最后再将结果链表反转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* @Description: 445. Add Two Numbers II
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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}
*/
const addTwoNumbers = function(l1, l2) {
let reL1 = reverseList(l1)
let reL2 = reverseList(l2)
let dummy = new ListNode()
let cur = dummy
let carry = 0

while (reL1 !== null || reL2 !== null || 1 === carry) {
let sum = 0
if (reL1 !== null) {
sum += reL1.val
reL1 = reL1.next
}
if (reL2 !== null) {
sum += reL2.val
reL2 = reL2.next
}
sum += carry
carry = Math.floor(sum / 10)
cur.next = new ListNode(sum % 10)
cur = cur.next
}
return reverseList(dummy.next)
}

function reverseList (head) {
if (head === null) {
return head
}
let pre = null
let cur = head
while (cur !== null) {
let temp = cur.next
cur.next = pre
pre = cur
cur = temp
}
return pre
}
方法二:栈

利用栈先入后出的特性,将两个链表依次压入栈,然后从栈中取出每个节点相加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
* @Description: 445. Add Two Numbers II
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @description: 通过栈来解决
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
const addTwoNumbers = function(l1, l2) {
let stack1 = []
let stack2 = []
let cur1 = l1
let cur2 = l2
while (cur1 !== null) {
stack1.push(cur1)
cur1 = cur1.next
}
while (cur2 !== null) {
stack2.push(cur2)
cur2 = cur2.next
}

let cur = null
let carry = 0
while (stack1.length || stack2.length || carry === 1) {
let sum = 0
if (stack1.length) {
sum += stack1.pop().val
}
if (stack2.length) {
sum += stack2.pop().val
}
sum += carry
let newHead = new ListNode(sum % 10, cur)
cur = newHead
carry = Math.floor(sum / 10)
}
return cur
}