为了账号安全,请及时绑定邮箱和手机立即绑定

Golang 自定义单链表的误区

Golang 自定义单链表的误区

Go
翻翻过去那场雪 2022-06-21 10:47:01
至于我,这是对第三个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 mainimport "fmt"// Linked List Codetype 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 Codetype 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)}
查看完整描述

1 回答

?
缥缈止盈

TA贡献2041条经验 获得超4个赞

list.tail.next = newNode设置的唯一原因list.head.next = newNode是,在操作时list.tail == list.head

在您的代码中,尽管我只看到 head 等于 tail,但前提是列表有一个元素。


查看完整回答
反对 回复 2022-06-21
  • 1 回答
  • 0 关注
  • 253 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号