golang go语言 实现链表
package main import ( "errors" "fmt" "strconv" ) type List struct { Length int Head *Node } type Node struct { NextNode *Node Value int } func (list *List) IsEmpty() bool { return list.Length == 0 } func (list *List) Append(value int) { list.Length += 1 if list.Head == nil { list.Head = &Node{Value: value} return } lastNode := list.Head for lastNode.NextNode != nil { lastNode = lastNode.NextNode } lastNode.NextNode = &Node{Value: value} } func (list *List) Delete(index int) error { if index + 1 > list.Length { return errors.New("index out of range") } list.Length -= 1 if index == 0{ list.Head = list.Head.NextNode return nil } indexNode := list.Head for i := index; i > 1; i-- { indexNode = indexNode.NextNode } if indexNode.NextNode != nil { indexNode.NextNode = indexNode.NextNode.NextNode } else { indexNode.NextNode = nil } return nil } func (list *List) String() string { var ret string node := list.Head for node.NextNode != nil { ret += strconv.Itoa(node.Value) + "," node = node.NextNode } ret += strconv.Itoa(node.Value) return ret } func (list *List) Insert(index, value int) error { if index + 1 > list.Length { return errors.New("index out of range") } list.Length++ if index == 0{ list.Head = &Node{Value:value, NextNode:list.Head} return nil } indexNode := list.Head for i := index; i > 1; i-- { indexNode = indexNode.NextNode } tempNode := &Node{Value: value, NextNode: indexNode.NextNode} indexNode.NextNode = tempNode return nil } func main() { a := List{} for i := 0; i < 10; i++ { a.Append(i) } fmt.Println(a.String()) if err := a.Insert(9, 99); err != nil{ fmt.Println(err) } fmt.Println(a.String()) }