Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import "fmt"
- // Stack describes a struct containing stack slice
- // e is a slice of strings allowing pushing/poping strincs
- // from the stack.
- type Stack struct {
- els []string
- }
- // Push adds a string to the top of the stack
- func (st *Stack) Push(s string) {
- st.els = append(st.els, s)
- }
- // Pop removes the top most element
- func (st *Stack) Pop() string {
- idx := len(st.els) - 1
- s := st.els[idx]
- st.els = st.els[0:idx]
- return s
- }
- // IsEmpty returns true if the stack is empty
- func (st *Stack) IsEmpty() bool {
- return st.Len() == 0
- }
- // Peek returns the top most element without removing it from the stack
- func (st *Stack) Peek() string {
- return st.els[len(st.els)-1]
- }
- // Len returns the number of elements on the stack
- func (st *Stack) Len() int {
- return len(st.els)
- }
- // Reset emptys the stack
- func (st *Stack) Reset() {
- st.els = []string{}
- }
- func main() {
- // Init new stack
- st := Stack{}
- // Push a few elements on the stack
- st.Push("Foo")
- st.Push("Bar")
- fmt.Println(st.Peek()) // "Bar"
- fmt.Println(st.Len()) // 2
- fmt.Println(st.Pop()) // "Bar"
- fmt.Println(st.Len()) // 1
- fmt.Println(st.IsEmpty()) // false
- st.Reset()
- fmt.Println(st.IsEmpty()) // true
- fmt.Println(st.Len()) // 0
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement