Year-End Discount: 10% OFF 1-year and 20% OFF 2-year subscriptions!

Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

stack
golang
data structure

How to implement a stack in Golang

Educative Answers Team

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. πŸ’ͺ

A stack is an ordered data structure that follows the Last-In-First-Out (LIFO) principle. Stacks are most easily implemented in Golang using slices:

  • An element is pushed to the stack with the built-in append function.
  • The element is popped from the stack by slicing off the top element.
svg viewer

Code

An implementation of a stack is shown below:

package main
import "fmt"
type Stack []string
// IsEmpty: check if stack is empty
func (s *Stack) IsEmpty() bool {
return len(*s) == 0
}
// Push a new value onto the stack
func (s *Stack) Push(str string) {
*s = append(*s, str) // Simply append the new value to the end of the stack
}
// Remove and return top element of stack. Return false if stack is empty.
func (s *Stack) Pop() (string, bool) {
if s.IsEmpty() {
return "", false
} else {
index := len(*s) - 1 // Get the index of the top most element.
element := (*s)[index] // Index into the slice and obtain the element.
*s = (*s)[:index] // Remove it from the stack by slicing it off.
return element, true
}
}
func main() {
var stack Stack // create a stack variable of type Stack
stack.Push("this")
stack.Push("is")
stack.Push("sparta!!")
for len(stack) > 0 {
x, y := stack.Pop()
if y == true {
fmt.Println(x)
}
}
}

Explanation

  • A type is made for a list called Stack. This allows us to create methods on Stack, just like the methods of a class.
  • The Push and Pop methods are implemented on lines 12βˆ’1412-14 and 17βˆ’2617-26, respectively. The Pop method utilizes the IsEmpty helper function to cater to the exception that occurs when the stack is empty.
  • In the main function, the stack is populated with three strings. The values stacked in the stack are then popped, notice the order in which they are printed. The output confirms that the stack correctly follows the LIFO principle.

Note that the stack is initialized to contain strings. Changing the type to interface{} would allow the stack to work for any data type.

RELATED TAGS

stack
golang
data structure
Copyright Β©2022 Educative, Inc. All rights reserved

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. πŸ’ͺ

Keep Exploring
Related Courses