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:
- Save the code in a file named
stack.go
. - Open a terminal or command prompt.
- Navigate to the directory where the file is stored.
- 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.