Research on Go language data structure: application of queue and stack

PHPz
Release: 2024-04-08 12:57:01
Original
845 people have browsed it

In the Go language, the queue follows the first-in-first-out (FIFO) principle and is implemented using the list package in the standard library. It is often used in messaging systems; the stack follows the last-in-first-out (LIFO) principle and is often used for function call tracking and bracket matching. , which can be implemented using slices.

Research on Go language data structure: application of queue and stack

Go language data structure talk: application of queue and stack

Queue

Queue is a data structure that adheres to the first-in-first-out (FIFO) principle. This means that the earliest elements entered into the queue will be removed first. Queues are useful in the following scenarios:

  • Message delivery systems, such as message queues
  • Buffers, such as network request queues

Go Implementation of queues in the language

The most common way to implement queues in the Go language is to use container/liststandard library package:

import (
    "container/list"
)

// 定义队列类型
type Queue struct {
    items *list.List
}

// 创建队列
func NewQueue() *Queue {
    return &Queue{
        items: list.New(),
    }
}

// 进队
func (q *Queue) Enqueue(item interface{}) {
    q.items.PushBack(item)
}

// 出队
func (q *Queue) Dequeue() interface{} {
    if q.IsEmpty() {
        return nil
    }
    front := q.items.Front()
    q.items.Remove(front)
    return front.Value
}

// 判断队列是否为空
func (q *Queue) IsEmpty() bool {
    return q.items.Len() == 0
}
Copy after login

Practical combat Case: Message Queue

Message queue is a typical application scenario of queue. We can use the queue in the Go language to implement a message queue:

func main() {
    // 创建消息队列
    queue := NewQueue()

    // 向队列发送消息
    queue.Enqueue("消息 1")
    queue.Enqueue("消息 2")

    // 接收消息
    for {
        msg := queue.Dequeue()
        if msg == nil {
            break
        }
        fmt.Println(msg)
    }
}
Copy after login

Stack

The stack is a data structure that adheres to the last-in-first-out (LIFO) principle. This means that the last element added to the stack will be removed first. The stack is very useful in the following scenarios:

  • Function call tracing
  • Bracket matching

Implementation of stack in Go language

The simplest way to implement the stack in the Go language is to use slicing:

// 定义栈类型
type Stack []interface{}

// 进栈
func (s *Stack) Push(item interface{}) {
    *s = append(*s, item)
}

// 出栈
func (s *Stack) Pop() interface{} {
    if s.Empty() {
        return nil
    }
    top := (*s)[len(*s)-1]
    *s = (*s)[:len(*s)-1]
    return top
}

// 判断栈是否为空
func (s *Stack) Empty() bool {
    return len(*s) == 0
}
Copy after login

Practical case: bracket matching

The stack is a checker for bracket matching Good tool:

func isBalanced(expr string) bool {
    stack := Stack{}
    for _, char := range expr {
        if char == '(' || char == '[' || char == '{' {
            stack.Push(char)
        } else if char == ')' || char == ']' || char == '}' {
            if stack.Empty() {
                return false
            }
            top := stack.Pop()
            if (char == ')' && top != '(') || (char == ']' && top != '[') || (char == '}' && top != '{') {
                return false
            }
        }
    }
    return stack.Empty()
}
Copy after login

The above is the detailed content of Research on Go language data structure: application of queue and stack. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template