Go:双向链表实现 panic 错误。

huangapple go评论99阅读模式
英文:

Go : doubly linked list implementing panic error

问题

更正:

链接 #1 http://play.golang.org/p/CKRNyWYF8X

链接 #2 http://play.golang.org/p/oT2yKzFwep

从第一个链接中,我确定 panic 错误来自于这段代码:

func (A *DoublyLinkedList) AddHead(input_value interface{}) {
  temp_node := &Node{value: input_value, prev: nil, next: A.head}
  original_head_node := A.head
  original_head_node.prev = temp_node
  A.length++
}

但是当我在双向链表中使用这段代码时,它稍后会发生 panic。并且仍然失败,因为下面这段代码没有将原始头节点与前一个指针连接起来。

  func (A *DoublyLinkedList) AddHead(input_value interface{}) {
     A.head = NewNode(input_value, nil, A.head)
     A.length++
  }

这就是问题所在。这个代码有类似的问题。

  无法分配给 target_node.GetPrevNode().GetNextNode()

Go 不支持这种方式的指针引用吗?我通过每次需要获取指针时分配一个新变量来修复了这个问题。但是我在顶部的第一个问题仍然无法编译。

简而言之,在 Go 中如何在添加新元素时连接双向链表?

英文:

Correction:

Link #1 http://play.golang.org/p/CKRNyWYF8X

Link #2 http://play.golang.org/p/oT2yKzFwep

From the first link,
I am sure that the panic error comes from this

func (A *DoublyLinkedList) AddHead(input_value interface{}) {
  temp_node := &Node{value: input_value, prev: nil, next: A.head}
  original_head_node := A.head
  original_head_node.prev = temp_node
  A.length++
}

But when I use this for doubly linked list, it panics little later. And still fails because this one below does not connect the original head with previous pointer.

  func (A *DoublyLinkedList) AddHead(input_value interface{}) {
     A.head = NewNode(input_value, nil, A.head)
     A.length++
  }

This is the one. This one has the similar problem.

  cannot assign to target_node.GetPrevNode().GetNextNode()

Does go not support pointer reference this way? I did fix this just assigning a new variable every time I need to get the pointer. But my first question on the top still does not compile.

In short, how do I connect the doubly linked list when adding a new element in Go?

答案1

得分: 0

你需要在DoublyLinkedList中初始化属性。在NewDoublyLinkedList()中,你似乎正在创建对它的引用,并且有两个nil属性。

type DoublyLinkedList struct {
    head   *Node // nil
    tail   *Node // nil
    length int
}

当执行以下操作时:

original_head_node := A.head // A.head == nil
original_head_node.prev = temp_node // 你试图访问一个nil属性
英文:

You need to initialize the properties inside the DoublyLinkedList. It seems to me, you are currently creating a reference to it in NewDoublyLinkedList() with 2 nil properties.

type DoublyLinkedList struct {
	head   *Node // nil
	tail   *Node // nil
	length int
}

And when doing this

original_head_node := A.head // A.head == nil
original_head_node.prev = temp_node // You are trying to access a property in nil

huangapple
  • 本文由 发表于 2013年11月10日 13:16:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/19886542.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定