NOTE
两数相加
两数相加的 LeetCode 解题笔记。
这是历史学习笔记,可能存在过时或不完整的理解。
1. 题目描述
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
2. 思路
- 思路一
- 不考虑大数
- 把两个链表转换成数字相加,再将结果转换回链表
- 该实现按高位在前读取链表,与本页 LeetCode 题目“逆序存储”的定义不一致,仅保留为历史实现
- 思路二
- 数字是逆序存放的,因此相对链表翻转
- 从右往左加,得出最后的结果
- 将结果翻转
- 思路三
3. 实现
3.1. 不考虑大数
//时间:O(N)
//空间:O(1)
func addInList(head1 *ListNode, head2 *ListNode) *ListNode {
if head1 == nil {
return head2
}
if head2 == nil {
return head1
}
val1 := 0
for head1 != nil {
val1 = val1*10 + head1.Val
head1 = head1.Next
}
val2 := 0
for head2 != nil {
val2 = val2*10 + head2.Val
head2 = head2.Next
}
sum := val1 + val2
if sum == 0 {
return &ListNode{Val: 0}
}
var head *ListNode
for sum != 0 {
current := sum % 10
head = &ListNode{
Val: current,
Next: head,
}
sum /= 10
}
return head
}
3.2. 栈
package main
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
lst1 := listToSlice(l1)
lst2 := listToSlice(l2)
reverse(lst1)
reverse(lst2)
dummyHead := &ListNode{
}
i := len(lst1) - 1
j := len(lst2) - 1
jinwei := 0
for i >= 0 || j >= 0 || jinwei > 0 {
a := 0
b := 0
if i >= 0 {
a = lst1[i]
i--
}
if j >= 0 {
b = lst2[j]
j--
}
val := (a + b + jinwei) % 10
dummyHead.Next = &ListNode{
Val: val,
Next: dummyHead.Next,
}
jinwei = (a + b + jinwei) / 10
}
head := dummyHead.Next
dummyHead.Next = nil
return reverseList(head)
}
func reverseList(head *ListNode) *ListNode {
if head == nil {
return nil
}
var prev *ListNode
current := head
next := head.Next
for current != nil {
current.Next = prev
prev = current
current = next
if next != nil {
next = next.Next
}
}
return prev
}
func reverse(lst []int) {
left := 0
right := len(lst) - 1
for left < right {
lst[left], lst[right] = lst[right], lst[left]
left++
right--
}
}
func listToSlice(head *ListNode) []int {
lst := make([]int, 0)
current := head
for current != nil {
lst = append(lst, current.Val)
current = current.Next
}
return lst
}
3.3. 遍历链表
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
h1 := l1
h2 := l2
dummyHead := &ListNode{Val:-1}
d := dummyHead
jinwei := 0
for h1 != nil || h2 != nil || jinwei > 0 {
sum := 0
if h1 != nil {
sum += h1.Val
h1 = h1.Next
}
if h2 != nil {
sum += h2.Val
h2 = h2.Next
}
sum += jinwei
d.Next = &ListNode{Val:sum%10}
d = d.Next
jinwei = sum / 10
}
return dummyHead.Next
}
讨论
使用 GitHub 账号参与讨论,评论会保存在 GitHub Issues 中。在 GitHub 查看