我在 Golang 中有一個雙向鏈表。就是這個type node struct { value string next *node prev *node}type list struct { head *node tail *node length int}我想在列表的最后插入元素。所以我需要做三件事:-- 改變當前Last的下一個指針-- 改變新節(jié)點的prev指針-- 將新節(jié)點指向 nil我做的完全一樣,但是 prev 指針似乎沒有指向前一個最后一個節(jié)點,因為它沒有從后面打印出來。你能發(fā)現(xiàn)問題嗎?我在最后添加了“粉紅色”這個詞。這是它的功能。func (listReceiver *list) insertLast(incomingValue string) { printNewLine := fmt.Println newNode := node{value: incomingValue} currentNode := listReceiver.head if listReceiver.head == nil { listReceiver.head = &newNode listReceiver.tail = &newNode fmt.Printf("New head -- %s", listReceiver.head.value) printNewLine() listReceiver.length++ } else { for currentNode.next != nil { printNewLine(currentNode.value) currentNode = currentNode.next } currentNode.next = &newNode newNode.next = nil newNode.prev = currentNode fmt.Printf("New Tail -- %s ", newNode.value) printNewLine() listReceiver.length++ }}這些是打印語句Linked List From Front -- ->R->Kanak->Z->Zubin->A->Nani->US->Arjun->PinkLinked List From Tail -- ->Arjun->US->Nani->A->Zubin->Z->Kanak->R
1 回答

茅侃侃
TA貢獻1842條經驗 獲得超21個贊
編輯----
您已經有了列表的尾部,無需使用for currentNode.next != nil {}
. 只需將tail.next
和list.tail
指向 newNode。
在 else 塊中你需要設置listReceiver.tail = &newNode
在任何情況下listReceiver.tail = &newNode
都應設置為可以在if-else
塊外
- 1 回答
- 0 關注
- 102 瀏覽
添加回答
舉報
0/150
提交
取消