Last active
November 16, 2018 12:12
-
-
Save rogerwelin/82734a0b8da170584a93ee3573a0bd67 to your computer and use it in GitHub Desktop.
stack.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "errors" | |
| "fmt" | |
| ) | |
| type Stack struct { | |
| s []int | |
| } | |
| func NewStack() *Stack { | |
| stack := Stack{ | |
| s: make([]int, 0), | |
| } | |
| return &stack | |
| } | |
| func (s *Stack) push(val int) { | |
| s.s = append(s.s, val) | |
| } | |
| func (s *Stack) isEmpty() bool { | |
| if len(s.s) == 0 { | |
| return true | |
| } | |
| return false | |
| } | |
| func (s *Stack) pop() (int, error) { | |
| length := len(s.s) | |
| if length == 0 { | |
| return 0, errors.New("empty stack") | |
| } | |
| result := s.s[len(s.s)-1] | |
| s.s = s.s[:length-1] | |
| return result, nil | |
| } | |
| func main() { | |
| stack := NewStack() | |
| stack.push(1) | |
| stack.push(2) | |
| stack.push(3) | |
| stack.push(4) | |
| fmt.Println(stack.s) | |
| val, _ := stack.pop() | |
| fmt.Println(val) | |
| val, _ = stack.pop() | |
| fmt.Println(val) | |
| fmt.Println(stack.s) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment