SHARE
TWEET

Untitled

a guest Apr 22nd, 2019 61 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. // Stack describes a struct containing stack slice
  6. // e is a slice of strings allowing pushing/poping strincs
  7. // from the stack.
  8. type Stack struct {
  9.     els []string
  10. }
  11.  
  12. // Push adds a string to the top of the stack
  13. func (st *Stack) Push(s string) {
  14.     st.els = append(st.els, s)
  15. }
  16.  
  17. // Pop removes the top most element
  18. func (st *Stack) Pop() string {
  19.     idx := len(st.els) - 1
  20.     s := st.els[idx]
  21.     st.els = st.els[0:idx]
  22.     return s
  23. }
  24.  
  25. // IsEmpty returns true if the stack is empty
  26. func (st *Stack) IsEmpty() bool {
  27.     return st.Len() == 0
  28. }
  29.  
  30. // Peek returns the top most element without removing it from the stack
  31. func (st *Stack) Peek() string {
  32.     return st.els[len(st.els)-1]
  33. }
  34.  
  35. // Len returns the number of elements on the stack
  36. func (st *Stack) Len() int {
  37.     return len(st.els)
  38. }
  39.  
  40. // Reset emptys the stack
  41. func (st *Stack) Reset() {
  42.     st.els = []string{}
  43. }
  44.  
  45. func main() {
  46.     // Init new stack
  47.     st := Stack{}
  48.  
  49.     // Push a few elements on the stack
  50.     st.Push("Foo")
  51.     st.Push("Bar")
  52.  
  53.     fmt.Println(st.Peek())    // "Bar"
  54.     fmt.Println(st.Len())     // 2
  55.     fmt.Println(st.Pop())     // "Bar"
  56.     fmt.Println(st.Len())     // 1
  57.     fmt.Println(st.IsEmpty()) // false
  58.     st.Reset()
  59.     fmt.Println(st.IsEmpty()) // true
  60.     fmt.Println(st.Len())     // 0
  61. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top