This program demonstrates the implementation of a stack using an array (slice) in Go. The stack supports push, pop, peek, and empty operations, functioning as a LIFO (Last In First Out) data structure.

Program Code

package main

import (
    "fmt"
)

// Stack represents the stack structure
type Stack struct {
    items []int
}

// NewStack creates a new Stack
func NewStack() *Stack {
    return &Stack{items: []int{}}
}

// Push adds an item to the top of the stack
func (s *Stack) Push(item int) {
    s.items = append(s.items, item)
}

// Pop removes the top item from the stack and returns it
func (s *Stack) Pop() int {
    if len(s.items) == 0 {
        fmt.Println("Stack is empty")
        return -1 // Assuming -1 is an error value for empty stack
    }
    lastIndex := len(s.items) - 1
    item := s.items[lastIndex]
    s.items = s.items[:lastIndex]
    return item
}

// Peek returns the top item of the stack without removing it
func (s *Stack) Peek() int {
    if len(s.items) == 0 {
        fmt.Println("Stack is empty")
        return -1 // Assuming -1 is an error value for empty stack
    }
    return s.items[len(s.items)-1]
}

// IsEmpty returns true if the stack is empty
func (s *Stack) IsEmpty() bool {
    return len(s.items) == 0
}

func main() {
    stack := NewStack()
    stack.Push(1)
    stack.Push(2)
    fmt.Println("Top element:", stack.Peek())  // Outputs: Top element: 2
    fmt.Println("Pop element:", stack.Pop())  // Outputs: Pop element: 2
    fmt.Println("Pop element:", stack.Pop())  // Outputs: Pop element: 1
    fmt.Println("Is the stack empty?", stack.IsEmpty())  // Outputs: Is the stack empty? true
}

Explanation

  • Stack Structure: The stack is implemented using a slice to hold the items. The struct Stack contains a slice of integers as its underlying storage.
  • Operations:
    • Push adds an item to the end of the slice, which acts as the top of the stack.
    • Pop removes the last item from the slice, simulating the removal of the top item of the stack. It also handles the case where the stack is empty.
    • Peek returns the last item of the slice without removing it, providing a view of the top item of the stack. It also checks if the stack is empty.
    • IsEmpty checks and returns whether the stack is empty.

 

Running the Program

To execute this Go program:

  1. Save the code in a file named stack.go.
  2. Open a terminal or command prompt.
  3. Navigate to the directory where the file is stored.
  4. Run the program by typing go run stack.go.

The output will demonstrate the functionality of the stack, showing the results of pushes, pops, and other operations, validating that the stack performs as expected according to the LIFO principle. Adjust the main function to test different scenarios and observe the behavior of the stack under various operations.

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)