向链表插入新节点时应该考虑哪些潜在错误?

问题描述 投票:0回答:1

我是 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
}
go linked-list
1个回答
0
投票

您的函数处理此操作最常见的错误情况,即超出范围的索引。但是,您还需要考虑其他一些潜在问题:

  1. 负索引。 您应该在函数的开头添加一个检查,以便在索引小于零时返回错误。
  2. 无列表。如果列表本身 (
    l
    ) 为零,调用
    l.Insert()
    将导致运行时恐慌。将
    L
    结构体设为私有,将
    new
    函数设为公开,以便用户仅使用
    New
    函数即可创建列表。
© www.soinside.com 2019 - 2024. All rights reserved.