How to Create a Stack in Go
Like a queue, the stack data structure can store objects, allowing the user to add and remove objects from it. In contrast to a queue, a stack uses the “Last In, First out” (LIFO) principle to do this. Similarly to a queue, the best way to implement a stack is by creating a struct. Many of the methods for the stack struct were already implemented for the queue struct in this blog post. Therefore, we have the following starter code:
type Stack struct {
elements []int // stores the objects in the stack
size int // the maximum size of the stack
}
func (s *Stack) GetLength() int {
return len(s.elements) // return current length of the stack
}
func (s *Stack) Add(element int) {
if s.GetLength() == s.size { // if the stack is at max length, don't add new element
fmt.Println("Stack is full")
return
} else {
s.elements = append(s.elements, element)
return
}
}
We then define a new method called Pop with the following implementation:
func (s *Stack) Pop() int {
if s.GetLength() == 0 { // if stack is empty, there is nothing to pop
fmt.Println("Stack is empty")
return 0
} else if s.GetLength() == 1 {
temp := s.elements[0]
s.elements = s.elements[:0] // if current length is 1, stack becomes empty
return temp
} else {
length := s.GetLength()
temp := s.elements[length-1]
s.elements = s.elements[:length-1]
return temp // return the popped element
}
}
We can then define the main function to create and modify a stack object:
import "fmt"
func main() {
s := Stack{size: 3} // creates a stack with a max size of 3
s.Add(1)
s.Add(2)
s.Add(3)
s.Add(4) // Stack is full
fmt.Println(s.elements) // [1, 2, 3]
elem1 := s.Pop()
elem2 := s.Pop()
elem3 := s.Pop()
fmt.Println(elem1, elem2, elem3) // 3, 2, 1
s.Pop() // Stack is empty
fmt.Println(s.elements) // []
}
The stack data structure is now implemented!