2 Star 2 Fork 8

王布衣/gox

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
arraystack.go 2.49 KB
一键复制 编辑 原始数据 按行查看 历史
王布衣 提交于 2023-06-07 20:08 . 修订部分util工具库
// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package arraystack implements a stack backed by array list.
//
// Structure is not thread safe.
//
// Reference: https://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29#Array
package arraystack
import (
"fmt"
"gitee.com/quant1x/gox/util/arraylist"
"gitee.com/quant1x/gox/util/internal"
"strings"
)
func assertStackImplementation() {
var _ internal.Stack = (*Stack)(nil)
}
// Stack holds elements in an array-list
type Stack struct {
list *arraylist.List
}
// New instantiates a new empty stack
func New() *Stack {
return &Stack{list: arraylist.New()}
}
// Push adds a value onto the top of the stack
func (stack *Stack) Push(value interface{}) {
stack.list.Add(value)
}
// Pop removes top element on stack and returns it, or nil if stack is empty.
// Second return parameter is true, unless the stack was empty and there was nothing to pop.
func (stack *Stack) Pop() (value interface{}, ok bool) {
value, ok = stack.list.Get(stack.list.Size() - 1)
stack.list.Remove(stack.list.Size() - 1)
return
}
// Peek returns top element on the stack without removing it, or nil if stack is empty.
// Second return parameter is true, unless the stack was empty and there was nothing to peek.
func (stack *Stack) Peek() (value interface{}, ok bool) {
return stack.list.Get(stack.list.Size() - 1)
}
// Empty returns true if stack does not contain any elements.
func (stack *Stack) Empty() bool {
return stack.list.Empty()
}
// Size returns number of elements within the stack.
func (stack *Stack) Size() int {
return stack.list.Size()
}
// Clear removes all elements from the stack.
func (stack *Stack) Clear() {
stack.list.Clear()
}
// Values returns all elements in the stack (LIFO order).
func (stack *Stack) Values() []interface{} {
size := stack.list.Size()
elements := make([]interface{}, size, size)
for i := 1; i <= size; i++ {
elements[size-i], _ = stack.list.Get(i - 1) // in reverse (LIFO)
}
return elements
}
// String returns a string representation of container
func (stack *Stack) String() string {
str := "ArrayStack\n"
values := []string{}
for _, value := range stack.list.Values() {
values = append(values, fmt.Sprintf("%v", value))
}
str += strings.Join(values, ", ")
return str
}
// Check that the index is within bounds of the list
func (stack *Stack) withinRange(index int) bool {
return index >= 0 && index < stack.list.Size()
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/quant1x/gox.git
git@gitee.com:quant1x/gox.git
quant1x
gox
gox
v1.15.5

搜索帮助

23e8dbc6 1850385 7e0993f3 1850385