至于我,這是對第三個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條經(jīng)驗 獲得超4個贊
list.tail.next = newNode
設(shè)置的唯一原因list.head.next = newNode
是,在操作時list.tail == list.head
。
在您的代碼中,盡管我只看到 head 等于 tail,但前提是列表有一個元素。
- 1 回答
- 0 關(guān)注
- 240 瀏覽
添加回答
舉報
0/150
提交
取消