Implement Stack and Queue in golang

Sourav Patnaik
3 min readJan 28, 2021
image copyright to sourav patnaik

Stack (LIFO), and Queue(FIFO) can be easily implemented using Slice in golang. Golang provides a built in function called “append()” which helps in appending an element to the end of a slice which serves our purpose to adding elements to stack and queue. We can even create a new slice by “slicing” an existing slice which will serve our purpose to give us a new stack and queue after pop() and dequeue() operation respectively.

Below is a basic example of stack, which stores numeric values. You can give a try to store string, boolean, array, map, struct even slice type in stack.

stack push, pop, isempty functions

isEmpty() will check if slice is empty or not, popping elements from an empty slice will return nil.

push() appends elements to slice.

pop() first check if slice is empty or not, ‘pop’ points to the last most element in stack. After that we are creating a new slice which contains first to second last element (which means we popped out the last element from our stack). Point to note, our new slice still points to the original slice, reason, slice pointers.

Below is the code to push and pop elements to out stack.

push and pop elements to stack

You can add more validation checks in the functions.

We pushed and popped 10 elements into our stack, after that we will just give a try to pop element from our empty stack.

Below is the output:

After Push, Elements in Stack:  [10 9 8 7 6 5 4 3 2 1]
Stack length 10 capacity 16
1 popped
2 popped
3 popped
4 popped
5 popped
6 popped
7 popped
8 popped
9 popped
10 popped
After Pop, Elements in Stack: []
Stack length 0 capacity 16
Stack is empty.

find the full code for stack here.

Logic for push() in stack and enqueue() in queue is same.

Below is the logic for dequeue().

Here we are taking out the first element form the queue and the new queue ‘q’ is points to second element to the last. If you compare dequeue() with pop(), it’s quite same.

find the full code for queue here.

Below is the output:

After Enqueue, Elements in Queue:  [1 2 3 4 5 6 7 8 9 10]
Queue length 10 capacity 16
1 dequeued
2 dequeued
3 dequeued
4 dequeued
5 dequeued
6 dequeued
7 dequeued
8 dequeued
9 dequeued
10 dequeued
After Dequeue, Elements in Queue: []
Queue length 0 capacity 6
Queue is empty.

For more examples, follow here.

--

--