Skip to content

Instantly share code, notes, and snippets.

@lubiksss
Created April 15, 2022 15:01
Show Gist options
  • Save lubiksss/1603083d656f4d99f896613d6344a9c8 to your computer and use it in GitHub Desktop.
Save lubiksss/1603083d656f4d99f896613d6344a9c8 to your computer and use it in GitHub Desktop.
test for golang stack
package main
import (
"errors"
"fmt"
)
func main() {
testStack := newStack()
testStack.push(1)
testStack.push(2)
testStack.push(3)
testStack.push(4)
fmt.Println(testStack.LinkedList)
fmt.Println(testStack.size())
fmt.Println(testStack.pop())
fmt.Println(testStack.LinkedList)
fmt.Println(testStack.size())
}
type Stack struct {
topOfStack int
LinkedList []int
}
func newStack() Stack {
return Stack{
topOfStack: 0,
LinkedList: make([]int, 0),
}
}
func (s Stack) size() int {
return s.topOfStack
}
func (s *Stack) push(element int) {
s.topOfStack += 1
s.LinkedList = append(s.LinkedList, element)
}
func (s *Stack) pop() (int, error) {
if s.topOfStack == 0 {
return 0, errors.New("no elements in Stack")
}
s.topOfStack -= 1
popedElement := s.LinkedList[s.topOfStack]
s.LinkedList = s.LinkedList[:s.topOfStack]
return popedElement, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment