dqpwdai095465 2015-05-19 01:29 采纳率: 100%
浏览 28
已采纳

在Go中实现堆栈以存储结构的正确方法是什么?

I'm trying to make a stack that will store a series of Huffman Tree structs. Currently I'm using an implementation that I found on github.

package util

type item struct {
    value interface{}
    next  *item
}

//Stack the implementation of stack
//this stack is not thread safe!
type Stack struct {
    top  *item
    size int
}
// Basic stack methods...

The problem is that when I store my Huffman tree structs in the stack I can't use any of the fields of the Huffman tree such as left/right child.

package huffmantree

type HuffmanTree struct {
    freq   int
    value  byte
    isLeaf bool
    left   *HuffmanTree
    right  *HuffmanTree
    code   []bool
    depth  int
}

How am I supposed to implement a stack in Go which will correctly store structs and allow access to their fields?

Edit: I tried replacing the interface {} part with huffmantree.HuffmanTree (huffmantree struct) and got this error message:

can't load package: import cycle not allowed
package github.com/inondle/huffman/util
    imports github.com/inondle/huffman/huffmantree
    imports github.com/inondle/huffman/util
import cycle not allowed

My guess would be that the huffmantree class imports the util package and the stack has to import the huffmantree package so there is some sort of conflict? Anyone know what went wrong?

  • 写回答

1条回答 默认 最新

  • dongtaogou6226 2015-05-19 02:09
    关注

    The right way in go to implement a stack is simply to use a slice.

    stack := []*HuffmanTree{}
    

    You can push to the stack using append, and pop by writing:

    v, stack := stack[len(stack)-1], stack[:len(stack)-1]
    

    You could encapsulate it into its own type if you prefer, but a slice is easier to understand.

    type Stack []*HuffmanTree{}
    
    func NewStack() *Stack {
        var s []*HuffmanTree
        return (*Stack)(&s)
    }
    
    func (s *Stack) Pop() *HuffmanTree {
        v = (*s)[len(*s)-1]
        *s = (*s)[:len(*s)-1]
        return v
    }
    
    func (s *Stack) Push(h *HuffmanTree) {
        *s = append(*s, h)
    }
    

    As icza observes, if the stacks live longer than the HuffmanTree objects, you may wish to zero the just-popped entry in your stack to allow the garbage collector to collect unreferenced objects.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog