Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Stack Implementation and Usage | Section
Go Data Structures

bookStack 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

  1. Define a Stack type using a struct with a slice field to hold the elements;
  2. Create methods on the Stack type for Push, Pop, Peek, and IsEmpty;
  3. 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

main.go

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
package 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) } }
question mark

Which of the following statements about stack operations in Go are correct

Select all correct answers

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 6

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 1. Kapittel 6
some-alt