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.

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

报告相同问题?

悬赏问题

  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?