Golang 自定义单链表的误区

至于我,这是对第三个if语句的误解。为什么list.tail.next = newNode也向head.next添加元素?


func (list *SingleLinkedList) Add(v int) {

    newNode := &SLLNode{value: v}

    if list.head == nil {

        list.head = newNode

    } else if list.tail == list.head {

        list.head.next = newNode

    } else if list.tail != nil {

        list.tail.next = newNode

    }

    list.tail = newNode

}

这是一个编译的程序示例:


package main


import "fmt"


// Linked List Code

type SingleLinkedList struct {

    head *SLLNode

    tail *SLLNode

}


func NewSingleLinkedList() *SingleLinkedList {

    return new(SingleLinkedList)

}


func (list *SingleLinkedList) Add(v int) {

    newNode := &SLLNode{value: v}

    if list.head == nil {

        list.head = newNode

    } else if list.tail == list.head {

        list.head.next = newNode

    } else if list.tail != nil {

        list.tail.next = newNode

    }

    list.tail = newNode

}


func (list *SingleLinkedList) String() string {

    stringResult := ""

    for n := list.head; n != nil; n = n.next {

        stringResult += fmt.Sprintf(" {%d} ", n.GetValue())

    }

    return stringResult

}


// Node Code

type SLLNode struct {

    next  *SLLNode

    value int

}


func (sNode *SLLNode) SetValue(v int) {

    sNode.value = v

}


func (sNode *SLLNode) GetValue() int {

    return sNode.value

}


func main() {

    // Linked List

    list:= NewSingleLinkedList()

    list.Add(4)

    list.Add(6)

    list.Add(3)

    list.Add(3)

    fmt.Println(list)

}


翻翻过去那场雪
浏览 254回答 1
1回答

缥缈止盈

list.tail.next = newNode设置的唯一原因list.head.next = newNode是,在操作时list.tail == list.head。在您的代码中,尽管我只看到 head 等于 tail,但前提是列表有一个元素。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go