亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在鏈表末尾插入項目

在鏈表末尾插入項目

Go
喵喵時光機 2021-12-20 15:44:06
我很新去和deicide來實現一個鏈表。這是我的源代碼package mainimport "fmt"type Node struct {  value int  next *Node}func main() {  var head *Node  for i := 1; i <= 10; i++ {    insert(&head, i)  }  print_list(head)}func print_list(node_pointer *Node) {  if (node_pointer == nil) {    return  } else {    node := *node_pointer    fmt.Printf("%d\n", node.value)    print_list(node.next)  }}func insert(node_pointer **Node, // pointer to a pointer to a Node    value int) {  var new_node Node  new_node.value = value  if (*node_pointer == nil) {    fmt.Printf("Empty list\n")    *node_pointer = &new_node  } else {    var cur_node Node = **node_pointer    for cur_node.next != nil {      cur_node = *cur_node.next    }    cur_node.next = &new_node    fmt.Printf("Add %d\n", (*cur_node.next).value)      }}輸出是:Empty listAdd 2Add 3Add 4Add 5Add 6Add 7Add 8Add 9Add 101換句話說,我不能在鏈表的末尾插入一個新節點。我相信它是由cur_node.next = &new_node僅在本地進行更新引起的,但不知道如何解決此問題。
查看完整描述

2 回答

?
ibeautiful

TA貢獻1993條經驗 獲得超6個贊

問題出在您的插入功能中 - 這是一個更正的版本


func insert(node_pointer **Node, // pointer to a pointer to a Node

    value int) {

    var new_node Node

    new_node.value = value


    if *node_pointer == nil {

        fmt.Printf("Empty list\n")

        *node_pointer = &new_node

    } else {

        var cur_node *Node = *node_pointer

        for cur_node.next != nil {

            cur_node = cur_node.next

        }

        cur_node.next = &new_node

        fmt.Printf("Add %d\n", (*cur_node.next).value)

    }

}


查看完整回答
反對 回復 2021-12-20
?
翻翻過去那場雪

TA貢獻2065條經驗 獲得超14個贊

你的錯誤是因為你得到了節點值,而不是這里的指針:

    var cur_node Node = **node_pointer

*note_pointer是一個指向列表頭的指針,但你正在使用**node_pointer,然后你得到值,然后將此值復制到cur_node,然后新節點將被附加到cur_node,與頭節點無關。所以當你打印表單頭節點時,你可以只獲取頭節點的值。

固定解決方案就像@Nick Craig-Wood 所說的。


查看完整回答
反對 回復 2021-12-20
  • 2 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號