Simulating Stacks and Queues in Go

Introduction: Stacks and Queues

Welcome to an exciting exploration of two fundamental data structures: Stacks and Queues! Data structures store and organize data in a structured and efficient manner. Stacks and Queues are akin to stacking plates and standing in a line, respectively. Intriguing, isn't it? Let's dive in!

Stacks: Last In, First Out (LIFO)

A Stack adheres to the "Last In, First Out" or LIFO principle. It's like a pile of plates where the last plate added is the first one to be removed. In Go, we can simulate stack behavior using slices, which are dynamic and allow adding and removing elements easily. The primary methods we'll mimic for stack operations include Push, Pop, and Top:

  • Push: Adds an element to the top of the stack.
  • Pop: Removes the top element from the stack.
  • Top: Returns the top element of the stack without removing it.

Let's explore this in code:

package main

import (
    "fmt"
)

// Stack represents a stack using a slice
type Stack struct {
    elements []string
}

// Push adds an element to the top of the stack
func (s *Stack) Push(element string) {
    s.elements = append(s.elements, element) // Appends the element to the slice
}

// Pop removes the top element from the stack
func (s *Stack) Pop() string {
    if len(s.elements) == 0 {
        return "No elements to remove!"
    }
    topElement := s.elements[len(s.elements)-1] // Get the last element
    s.elements = s.elements[:len(s.elements)-1] // Remove the last element
    return topElement
}

// Top returns the top element of the stack without removing it
func (s *Stack) Top() string {
    if len(s.elements) == 0 {
        return "No elements in the stack!"
    }
    return s.elements[len(s.elements)-1]
}

func main() {
    stack := Stack{}
    stack.Push("Element 1")      // Adding first element
    stack.Push("Element 2")      // Adding second element

    // Checking the top element, which is "Element 2"
    fmt.Println("Top element:", stack.Top()) // Outputs: Top element: Element 2

    // Removing the top element, which is "Element 2"
    fmt.Println("Removed:", stack.Pop()) // Outputs: Removed: Element 2
}

Here, the Push function appends an element to the slice, just like adding a new plate on the top. The Pop function retrieves and removes the last element of the slice, demonstrating the LIFO behavior. The Top function retrieves the last element added without removing it, allowing us to peek at the top of the stack.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal