至于我,这是对第三个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)
}
缥缈止盈
相关分类