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 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.