Pointers Golang自定义单链表
对我来说,这是对第三个if语句的误解。 为什么list.tail.next=newNode将元素添加到头部。next也要添加Pointers Golang自定义单链表,pointers,go,Pointers,Go,对我来说,这是对第三个if语句的误解。 为什么list.tail.next=newNode将元素添加到头部。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.
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)
}
list.tail.next=newNode
也设置list.head.next=newNode
的唯一原因是,在操作时list.tail==list.head
在您的代码中,虽然我只看到head等于tail,但前提是列表只有一个元素。在第三个if语句中,您在哪里看到
head.next
?它所做的只是通过查找最后一个元素(list.tail
),将下一个元素设置为新元素(list.tail.next=newNode
),并最终将尾部移动到新的最后一个元素(list.tail=newNode
),将新元素添加到列表的末尾<代码>列表。在这种情况下,不会触及标题。我也这么认为,但尝试使用此代码,您会惊讶于指针的模糊性。我现在将为你更新这篇文章head。下一篇当head
和tail
指向同一元素时,它将改变。否则它将保持不变。如果您发现其他情况,请显示您的代码。当您初始化此列表并向其中添加元素时,所有元素将逐步包含在head中。next。next。next…n-next制作一个,并在您的问题中发布。但是是的,第一个元素是头
,第二个是头。下一个是,第三个是头。下一个是,这就是链表的工作方式。这并不意味着head。next
在第二个元素之后更改。不客气,请注意,正因为如此,中间的else if list.tail==list.head
语句已过时。