Go Program to Implement a Stack Using Slices

1. Introduction

A stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means that the last element added to the stack will be the first element removed. In this blog post, we'll dive into a Go program that uses slices to implement the basic operations of a stack: push, pop, and peek.

2. Program Overview

The Go program will be structured as follows:

1. We'll define a Stack type based on a slice.

2. Implement the push, pop, and peek methods for the stack.

3. Demonstrate the stack's operations within the main function.

3. Code Program

// Package declaration
package main

// Importing necessary packages
import "fmt"

// Stack type based on a slice
type Stack []int

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

// Pop removes and returns the top item from the stack
func (s *Stack) Pop() int {
    res := (*s)[len(*s)-1]
    *s = (*s)[:len(*s)-1]
    return res
}

// Peek returns the top item from the stack without removing it
func (s *Stack) Peek() int {
    return (*s)[len(*s)-1]
}

// Main function demonstrating stack operations
func main() {
    var s Stack

    s.Push(1)
    s.Push(2)
    s.Push(3)

    fmt.Println("Top of the stack:", s.Peek())
    fmt.Println("Popped from stack:", s.Pop())
    fmt.Println("Stack after pop:", s)
}

Output:

Top of the stack: 3
Popped from stack: 3
Stack after pop: [1 2]

4. Step By Step Explanation

1. Stack Definition: We defined a new type Stack which is essentially a slice of integers. This will serve as our underlying data structure.

2. Push Operation: The Push method appends an element to the end of the slice, which represents the top of the stack.

3. Pop Operation: The Pop method removes the last element (the top of the stack) and returns its value.

4. Peek Operation: The Peek method returns the top element without modifying the stack.

5. Main Function: We demonstrate the operations of the stack by pushing three integers onto it, peeking to see the top, and then popping an element.

The beauty of Go slices makes it especially easy and efficient to implement a stack. This structure is not only a foundation in computer science but is also used in many real-world applications, from parsing expressions to tracking function calls.

Comments