思路&代码
需要考虑的核心点在于进位的处理方式,一个节点只能存储一个一位数字,所以有进位,就需要申请节点.在这一些特殊边界条件的处理.
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func (l *ListNode) Display() {
for h := l; h != nil; h = h.Next {
fmt.Println(h.Val)
}
fmt.Println("-------------------")
}
func AddLink(p, q *ListNode) *ListNode {
if p == nil && q == nil {
return nil
}
if p == nil && q != nil {
return q
}
if p != nil && q == nil {
return p
}
var f, s, t, h *ListNode = p, q, nil, nil
// 将所有节点先计算完成
for f != nil && s != nil {
data := f.Val + s.Val
n := &ListNode{
Val: data,
Next: nil,
}
if h == nil {
h = n
t = h
} else {
t.Next = n
t = t.Next
}
f = f.Next
s = s.Next
}
if f == nil {
t.Next = s
}
if s == nil {
t.Next = f
}
for m := h; m != nil; m = m.Next {
if m.Val >= 10 {
if m.Next == nil { // 末尾了,如果>=10,则需要新增一个节点,再处理节点的值
n := &ListNode{
Val: 0,
Next: nil,
}
m.Next = n
}
m.Val = m.Val % 10
m.Next.Val += 1
}
}
return h
}
func main() {
var l1, l2, t *ListNode = nil, nil, nil
l1 = &ListNode{
Val: 1,
Next: nil,
}
t = l1
n := &ListNode{
Val: 2,
Next: nil,
}
t.Next = n
t = t.Next
n = &ListNode{
Val: 8,
Next: nil,
}
t.Next = n
t = t.Next
// -------
l2 = &ListNode{
Val: 1,
Next: nil,
}
t = l2
n = &ListNode{
Val: 2,
Next: nil,
}
t.Next = n
t = t.Next
n = &ListNode{
Val: 8,
Next: nil,
}
t.Next = n
t = t.Next
l1.Display()
l2.Display()
AddLink(l1, l2).Display()
}
第二种:直接链表创建,注意一些边界值的处理:
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
var l3 *ListNode
var tail *ListNode
cur := 0
for l1 != nil && l2 != nil {
data := l1.Val + l2.Val + cur
cur = data / 10 // 下一轮的近位
node := &ListNode{
Val: data % 10,
Next: nil,
}
if l3 == nil {
l3 = node
tail = node
} else {
tail.Next = node
tail = tail.Next
}
l1 = l1.Next
l2 = l2.Next
}
// 5,5
if l1 == nil && l2 == nil {
if cur != 0 {
n := &ListNode{
Val: cur,
Next: nil,
}
tail.Next = n
tail = tail.Next
}
}
TooListFun := func(nl *ListNode) {
for nl != nil {
data := nl.Val + cur
if data == 10 {
cur = 1 // 等于10,近位1
} else {
cur = data / 10
}
node := &ListNode{
Val: data % 10,
Next: nil,
}
tail.Next = node
tail = tail.Next
nl = nl.Next
}
// 最后一个近位不为0需要再创建一个节点
if cur != 0 {
node := &ListNode{
Val: cur,
Next: nil,
}
tail.Next = node
tail = tail.Next
}
}
if l1 == nil && l2 != nil {
TooListFun(l2)
}
if l2 == nil && l1 != nil {
TooListFun(l1)
}
return l3
}