2 回答

TA貢獻1829條經驗 獲得超6個贊
基本問題是您永遠不會為結構指針分配內存。當你寫:
var list *ListNode
您已經創建了一個指向 ListNode 類型的指針,但您實際上并沒有為它分配任何內存。所以當你嘗試寫...
list.Val = i
您收到“無效內存地址”錯誤,因為您試圖取消引用未定義的指針。分配內存的一種方法是使用new()新的內置函數:
var list *ListNode = new(ListNode)
您還可以獲取結構的地址,如下所示:
list := &ListNode{}
上面顯示了正確的語法,但是如果您只是用var上面的聲明替換現有的聲明,您的代碼中仍然會有邏輯問題:您不想分配任何內存,直到您將第一個節點添加到列表中。這意味著我們要等到我們進入for循環內才能分配內存。
通過對您的代碼進行一些小的更改,我們得到:
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func main() {
var head, tail *ListNode
for i := 0; i <= 5; i++ {
node := new(ListNode)
node.Val = i
if tail == nil {
// This is the first node in the list, so just point head
// and tail at the new node.
tail = node
head = tail
} else {
// There is at least one node in the list, so attach the new
// node to the tail
tail.Next = node
tail = node
}
}
result := head
for result != nil {
fmt.Printf("%d\t", result.Val)
// Don't forget to increment to the next node!
result = result.Next
}
}
運行此代碼會產生:
0 1 2 3 4 5

TA貢獻1871條經驗 獲得超13個贊
您必須為列表節點分配內存。創建列表節點時,更新前一個節點中的 Next 字段或更新列表頭(如果這是第一個節點)。
var head *ListNode
// p is pointer to head or pointer to previous node's Next.
// We start with p set as pointer to the head.
p := &head
for i := 0; i <= 5; i++ {
// Allocate a new ListNode with Val initialized.
n := &ListNode{Val: i}
// Update head or previous node'a Next field.
*p = n
// The next iteration of the loop should update
// the Next field in the node that we just created.
p = &n.Next
}
// Loop while list node is not nil.
for n := head; n != nil; n = n.Next {
fmt.Println(n.Val)
}
https://go.dev/play/p/qUhza05kUFT
- 2 回答
- 0 關注
- 161 瀏覽
添加回答
舉報