Sitemap
Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Basic implementation of Stack data structure in Go

--

Dealing with Stack Data Structure in simple ways

When we talk about stack, we often encounter it in our daily lives — whether it’s organizing a bunch of plates or managing chairs at a function one on top of another.

Press enter or click to view image in full size
“Stack of plates” by Julia Taubitz on Unsplash

In computer science, Stack is one of the simplest but powerful linear data structure which organizes data in a simple, ordered way. It follows LIFO (Last In First Out) principle, meaning that last element added would always be the first element removed. Consider a stack of plates where you add a new plate on top, and you always remove the topmost plate first.

Some of the common operations supported by Stack are:

  1. Push - add an element to the top of stack
  2. Pop - remove the top element from the stack
  3. Top - returns the top element
  4. Empty - return true if stack is empty
  5. Size - returns size of the stack

Stack can be implemented using arrays and linked lists. In this article we will see array based stack implementation.

Get Ritesh Pawar’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s create an interface IStack having above stack operations:

Now, let’s implement the stack operations one by one.

  1. Push operation adds an element on top of the stack

2. Pop operation removes an element from the top of the stack, it will return false if the stack is empty.

3. Top operation returns the top element from the stack, it will return an error if the list is empty.

4. Empty operation returns true if the stack is empty, otherwise false

5. Size operation returns the number of elements in the stack

Note: The provided basic code is for reference purposes only and may require special handling in certain cases.

You can find the complete code here.

Conclusion:

In this story, we’ve learnt some basic knowledge of stack like:

  • A stack is a linear data structure, similar to arrays
  • The primary operations on a stack are push (adding an element to the top) and pop (removing an element from the top).
  • Real-world examples of stacks include undo-redo functionality in text editors, back and forward navigation in web browsers, and function calls in programming languages.

That’s it from my side. Any suggestions & corrections are highly welcomed.

Stay happy 😊 & keep reading.

--

--