Stack Implementation and Usage
Sveip for å vise menyen
Implementing a Stack in Go
A stack is a linear data structure that follows the Last-In, First-Out (LIFO) principle. This means the last element you add is the first one you remove. Stacks are used in applications such as undo functionality, browser history, and expression evaluation.
In Go, you can implement a stack using a slice. Slices provide dynamic resizing and efficient access to the end of the collection, making them well-suited for stack operations.
Stack Structure
- A stack has two primary operations:
- Push: Add an element to the top of the stack;
- Pop: Remove and return the element from the top of the stack.
- You can also include a Peek operation to view the top element without removing it;
- An IsEmpty method helps check if the stack has any elements.
Implementation Approach
- Define a
Stacktype using a struct with a slice field to hold the elements; - Create methods on the
Stacktype forPush,Pop,Peek, andIsEmpty; - Use Go's built-in slice operations to manage stack behavior efficiently.
This approach provides a simple, idiomatic, and efficient stack implementation in Go.
main.go
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960package main import ( "errors" "fmt" ) type Stack struct { items []int } func (s *Stack) Push(item int) { s.items = append(s.items, item) } func (s *Stack) Pop() (int, error) { if len(s.items) == 0 { return 0, errors.New("stack is empty") } lastIndex := len(s.items) - 1 item := s.items[lastIndex] s.items = s.items[:lastIndex] return item, nil } func (s *Stack) Peek() (int, error) { if len(s.items) == 0 { return 0, errors.New("stack is empty") } return s.items[len(s.items)-1], nil } func main() { stack := &Stack{} stack.Push(10) stack.Push(20) stack.Push(30) fmt.Println("Stack after pushing 10, 20, 30:", stack.items) top, _ := stack.Peek() fmt.Println("Peek:", top) popped, _ := stack.Pop() fmt.Println("Popped:", popped) fmt.Println("Stack after pop:", stack.items) stack.Push(40) fmt.Println("Stack after pushing 40:", stack.items) for len(stack.items) > 0 { item, _ := stack.Pop() fmt.Println("Popped:", item) } _, err := stack.Pop() if err != nil { fmt.Println("Error:", err) } }
Alt var klart?
Takk for tilbakemeldingene dine!
Seksjon 2. Kapittel 3
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Seksjon 2. Kapittel 3