Post

Stacks in Golang

Stacks in Golang

Hits

In Golang, a stack is a linear data structure that works on the Last-In-First-Out (LIFO) principle which means that the element which is pushed in the stack in last will be popped out first.

In general stacks has 2 operations_

  1. Push: Adds an element to the top of the stack.
  2. Pop: Removes and returns the element from the top of the stack.

But we can also implement_

  1. Peek (or Top): Returns the element from the top of the stack without removing it.
  2. isEmpty: Checks if the stack is empty.
  3. Size (or Length): Returns the number of elements currently in the stack.
Linked List

Fig: Stacks

Implementation of Stack in Golang_

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main

import "fmt"

type stack struct {
	items []interface{}
}

func (s *stack) Push(item interface{}) {
	s.items = append(s.items, item)
}

func (s *stack) Pop() interface{} {
	if len(s.items) == 0 {
		return nil
	}
	index := len(s.items) - 1
	item := s.items[index]
	s.items = s.items[:index]
	return item
}

func (s *stack) Peek() interface{} {
	if len(s.items) == 0 {
		return nil
	}
	return s.items[len(s.items)-1]
}

func (s *stack) IsEmpty() bool {
	return len(s.items) == 0
}

func (s *stack) Print() {
	fmt.Println("Stack:")
	for _, item := range s.items {
		fmt.Printf("%d->", item)
	}
	fmt.Println("\n")
}

func (s *stack) Length() int {
	return len(s.items)
}

func main() {
	stack := stack{}

	stack.Push(1)
	stack.Push(2)
	stack.Push(3)

	stack.Print()

	ln := stack.Length()
	fmt.Println("Length:", ln)
	fmt.Println("\n")

	fmt.Println("Peek:", stack.Peek())

	fmt.Println("Pop:", stack.Pop())
	fmt.Println("Pop:", stack.Pop())
	fmt.Println("Pop:", stack.Pop())

	fmt.Println("Is empty?", stack.IsEmpty())
}

Output

1
2
3
4
5
6
7
8
9
10
11
Stack:
1->2->3->

Length: 3


Peek: 3
Pop: 3
Pop: 2
Pop: 1
Is empty? true
This post is licensed under CC BY 4.0 by the author.