在Go中的LIFO容器

huangapple go评论68阅读模式
英文:

LIFO container in Go

问题

我需要使用具有push和pop操作的LIFO堆栈容器,但是container包中没有这样的容器。是每个程序员都应该自己编写,还是有一种方法可以使用其他数据结构作为堆栈(比如Python中的列表)?

英文:

I need to use LIFO stack container with push and pop operations, but container package doesn't have one. Is it supposed to be writen ad-hoc by every programmer, or there is a way to use other data structure as stack (like list in python)?

答案1

得分: 9

在Go语言或标准库中没有内置的栈类型。然而,你可以很简单地向切片中添加Push和Pop方法(与Python中列表的现有方法类似)。

type Stack []YourType

func (s *Stack) Push(v YourType) {
    *s = append(*s, v)
}

func (s *Stack) Pop() YourType {
    ret := (*s)[len(*s)-1]
    *s = (*s)[0 : len(*s)-1]

    return ret
}

非常直观。

英文:

There is no built-in stack type in Go or the standard libraries. However, you can add Push and Pop methods to a slice pretty simply (not unlike the existing methods on lists in python).

type Stack []YourType

func (s *Stack) Push(v YourType) {
    *s = append(*s, v)
}

func (s *Stack) Pop() YourType {
    ret := (*s)[len(*s)-1]
    *s = (*s)[0 : len(*s)-1]

    return ret
}

Pretty straightforward

答案2

得分: 3

stack是list的一个子集,golang有container/list库,用于实现一个简单的stack,这里是一个例子。

//后进先出
stack := list.New()
//stack的push使用PushBack
for i:=0;i<100;i++ {
	stack.PushBack(i)
}
//stack的获取顶部使用stack.Back()
//stack的弹出使用stack.Remove(stack.Back())
//stack的判空使用stack.Back() == nil
for stack.Back()!=nil {
	fmt.Println(stack.Back().Value)
	stack.Remove(stack.Back())
}
英文:

stack is a subset of list,golang has container/list library,which is simple for implement a stack,here is an example。

//last in first out
	stack := list.New()
    //stack push use PushBack
	for i:=0;i&lt;100;i++ {
		stack.PushBack(i)
	}
	//stack get top use stack.Back()
    //stack pop use stack.Remove(stack.Back())
    //stack isEmpty use stack.Back() == nil 
	for stack.Back()!=nil {
		fmt.Println(stack.Back().Value)
		stack.Remove(stack.Back())
	}

答案3

得分: 0

在标准库中没有container包。然而,LIFO只是一个栈,可以很容易地用切片等方式建模。因此,标准库中没有LIFO容器。

英文:

There's no container package in the stdlib. Yet, LIFO is just a stack, it's easily modelled by, for example, a slice. Hence no stdlib LIFO container.

huangapple
  • 本文由 发表于 2013年7月3日 04:13:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/17435019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定