我是 Go 新手。
我编写了一个函数,用于在链表中的给定索引处插入新节点。
除了超出范围的错误之外,我还应该考虑在此函数中处理哪些其他潜在错误?
package main
import (
"errors"
"fmt"
)
// Node represents an element in the linked list
type Node struct {
Value int
Next *Node
}
// L represents a linked list
type L struct {
head *Node
}
// new creates and returns a new instance of a linked list
func new() *L {
return &L{}
}
func (l *L) Insert(index int, val int) error {
if index == 0 {
l.head = &Node{Value: val, Next: l.head}
return nil
}
current := l.head
for i := 0; i < index-1; i++ {
if current == nil {
return errors.New("out of range")
}
current = current.Next
}
if current == nil {
return errors.New("out of range")
}
current.Next = &Node{Value: val, Next: current.Next}
return nil
}
您的函数处理此操作最常见的错误情况,即超出范围的索引。但是,您还需要考虑其他一些潜在问题:
l
) 为零,调用 l.Insert()
将导致运行时恐慌。将 L
结构体设为私有,将 new
函数设为公开,以便用户仅使用 New
函数即可创建列表。