doucheng2210 2015-02-16 12:37
浏览 76
已采纳

在golang中寻找合理的堆栈实现?

So far my naive approach is

type stack []int

func (s *stack) Push(v int) {
    *s = append(*s, v)
}

func (s *stack) Pop() int {
    res:=(*s)[len(*s)-1]
    *s=(*s)[:len(*s)-1]
    return res
}

it works - playground, but looks ugly and has too much dereferencing. Can I do better?

  • 写回答

2条回答 默认 最新

  • douyihuaimao733955 2015-02-16 13:14
    关注

    It's a matter of style and personal taste, your code is fine (apart from not being thread safe and panicking if you pop from an empty stack). To simplify it a bit you can work with value methods and return the stack itself, it's slightly more elegant to some tastes. i.e.

    type stack []int
    
    func (s stack) Push(v int) stack {
        return append(s, v)
    }
    
    func (s stack) Pop() (stack, int) {
        // FIXME: What do we do if the stack is empty, though?
    
        l := len(s)
        return  s[:l-1], s[l-1]
    }
    
    
    func main(){
        s := make(stack,0)
        s = s.Push(1)
        s = s.Push(2)
        s = s.Push(3)
    
        s, p := s.Pop()
        fmt.Println(p)
    
    }
    

    Another approach is to wrap it in a struct, so you can also easily add a mutex to avoid race conditions, etc. something like:

    type stack struct {
         lock sync.Mutex // you don't have to do this if you don't want thread safety
         s []int
    }
    
    func NewStack() *stack {
        return &stack {sync.Mutex{}, make([]int,0), }
    }
    
    func (s *stack) Push(v int) {
        s.lock.Lock()
        defer s.lock.Unlock()
    
        s.s = append(s.s, v)
    }
    
    func (s *stack) Pop() (int, error) {
        s.lock.Lock()
        defer s.lock.Unlock()
    
    
        l := len(s.s)
        if l == 0 {
            return 0, errors.New("Empty Stack")
        }
    
        res := s.s[l-1]
        s.s = s.s[:l-1]
        return res, nil
    }
    
    
    func main(){
        s := NewStack()
        s.Push(1)
        s.Push(2)
        s.Push(3)
        fmt.Println(s.Pop())
        fmt.Println(s.Pop())
        fmt.Println(s.Pop())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置