Stack Implementation in Golang

1. Introduction

A Stack is a linear data structure that follows the Last In First Out (LIFO) principle, meaning the last element added to the stack is the first element removed from it. Common operations associated with a stack include push (to add an element) and pop (to remove the top element). Another utility operation is peek or top, which returns the top element without popping it.

2. Implementation Steps

1. Define a Stack type with a slice to hold elements.

2. Implement the push method to add an element to the top of the stack.

3. Implement the pop method to remove and return the top element. Check for stack underflow.

4. Implement the peek or top method to view the top element without removing it.

5. Optionally, add a method to check if the stack is empty.

3. Implementation in Golang

package main
import (
	"fmt"
	"errors"
)
type Stack []int
func (s *Stack) Push(v int) {
	*s = append(*s, v)
}
func (s *Stack) Pop() (int, error) {
	if len(*s) == 0 {
		return 0, errors.New("Stack is empty")
	}
	res := (*s)[len(*s)-1]
	*s = (*s)[:len(*s)-1]
	return res, nil
}
func (s *Stack) Peek() (int, error) {
	if len(*s) == 0 {
		return 0, errors.New("Stack is empty")
	}
	return (*s)[len(*s)-1], nil
}
func (s *Stack) IsEmpty() bool {
	return len(*s) == 0
}
func main() {
	var stack Stack
	stack.Push(5)
	stack.Push(10)
	stack.Push(15)
	fmt.Println("Top of the Stack:", stack.Peek())
	fmt.Println("Stack:", stack)
	popped, _ := stack.Pop()
	fmt.Println("Popped:", popped)
	fmt.Println("Stack after Pop:", stack)
}

Output:

Top of the Stack: 15
Stack: [5 10 15]
Popped: 15
Stack after Pop: [5 10]

Explanation:

1. A new data type Stack is defined as a slice of integers.

2. The Push method appends a value to the end of the slice, effectively pushing it onto the stack.

3. The Pop method checks for stack underflow by seeing if the length of the slice is 0. If it's not empty, it returns the last element and updates the slice by removing the last element.

4. The Peek method simply returns the last element of the slice without modifying it.

5. The IsEmpty method checks if the stack is empty by verifying if the length of the slice is 0.

6. The main function demonstrates the usage of the stack, its methods, and the output.

This Stack implementation in Golang provides a simple yet efficient way to utilize the LIFO principle in various applications.


Comments