到目前为止,我的天真方法是
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
}
Run Code Online (Sandbox Code Playgroud)
它工作 - 操场,但看起来很丑,并且有太多的解除引用.我可以做得更好吗?
Not*_*fer 56
这是一个风格和个人品味的问题,你的代码很好(除了不是线程安全和恐慌,如果你从空堆栈弹出).为了简化它,你可以使用值方法并返回堆栈本身,它对某些品味稍微优雅一些.即
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)
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是将它包装在一个结构中,这样你也可以轻松地添加一个互斥体来避免竞争条件,例如:
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())
}
Run Code Online (Sandbox Code Playgroud)
guy*_*kes 11
这是使用链接数据结构的LIFO实现
package stack
import "sync"
type element struct {
data interface{}
next *element
}
type stack struct {
lock *sync.Mutex
head *element
Size int
}
func (stk *stack) Push(data interface{}) {
stk.lock.Lock()
element := new(element)
element.data = data
temp := stk.head
element.next = temp
stk.head = element
stk.Size++
stk.lock.Unlock()
}
func (stk *stack) Pop() interface{} {
if stk.head == nil {
return nil
}
stk.lock.Lock()
r := stk.head.data
stk.head = stk.head.next
stk.Size--
stk.lock.Unlock()
return r
}
func New() *stack {
stk := new(stack)
stk.lock = &sync.Mutex{}
return stk
}
Run Code Online (Sandbox Code Playgroud)
小智 6
我相信如果我们能够利用 Go 的标准库而不是像 @guy_fawkes 那样创建自定义数据结构,那就太好了。尽管他做得很好,但这并不是使用单链表的标准方法。
为了以 O(1) 时间复杂度获取列表的尾部,我将使用双向链表。我用空间换时间。
我还采纳了 @Not_a_Golfer 的建议,向堆栈添加锁。
import (
"container/list"
"sync"
)
type Stack struct {
dll *list.List
mutex sync.Mutex
}
func NewStack() *Stack {
return &Stack{dll: list.New()}
}
func (s *Stack) Push(x interface{}) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.dll.PushBack(x)
}
func (s *Stack) Pop() interface{} {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.dll.Len() == 0 {
return nil
}
tail := s.dll.Back()
val := tail.Value
s.dll.Remove(tail)
return val
}
Run Code Online (Sandbox Code Playgroud)
单击此 Playground预览结果。