记录golang利用切片实现栈操作,附例子如下
//init stack as string type slice,send data of string with space splite
//return a stack with data
func InitWithStringSpliteSpace(stack []string, s string) []string {
for _, v := range strings.Split(s, " ") {
stack = append(stack, v)
}
return stack
}
//push a data on top of stack
//return a stack with data
func PushTop(stack []string, top string) []string {
return append(stack, top)
}
//get top data from a stack
//return top data
func GetTop(stack []string) string {
return stack[len(stack)-1]
}
//get top data from a stack and remove it,pop out stack
//return top data and stack
func GetAndRemoveTop(stack []string) (string, []string) {
return stack[len(stack)-1], stack[:len(stack)-1]
}
//remove top data form a stack
//return stack
func RemoveTop(stack []string) []string {
return stack[:len(stack)-1]
}
//remove index of data form a stack,the index is sort of stack
//return stack
func RemoveIndex(stack []string, i int) []string {
copy(stack[i:], stack[i+1:])
return stack[:len(stack)-1]
}
func main() {
var stack []string
s := "Hello Go Demo Project"
t := "Top"
stack = InitWithStringSpliteSpace(stack, s)
fmt.Println("InitWithStringSpliteSpace stack = ", stack)
stack = PushTop(stack, t)
fmt.Println("PushTop stack = ", stack)
fmt.Println("GetTop top = ", GetTop(stack))
t, stack = GetAndRemoveTop(stack)
fmt.Printf("GetAndRemoveTop stack = %s,top = %s\n", stack, t)
stack = RemoveTop(stack)
fmt.Println("RemoveTop stack = ", stack)
fmt.Println("RemoveIndex stack = ", RemoveIndex(stack, 2))
}