[数据结构]之队列

[数据结构]之队列
1 描述
队列是一种先进先出的线性数据结构。在队首出队,在队尾入队。

队列这个是和栈相对的。比如银行的排队机制

2 数据结构
属性:
元素数组 elemets

队尾位置 tail

元素个数 length(值为top+1)

方法:
NewQueue 初始化队列,创建空队列

clear 清除元素

IsEmpty 判断是否为空

offer 添加元素

poll 删除队首元素

peek 获取队首元素

3 go语言实现

    package main
    
    import (
        "fmt"
    )
    
    const CAP = 20
    
    type Queue struct {
        Elemets [CAP]string
        Tail    int
        Length  int
    }
    
    func NewQueue() *Queue {
        return &Queue{Tail: -1, Length: 0}
    }
    
    func (list *Queue) offer(elem string) error {
        if list.Tail == CAP-1 {
            return fmt.Errorf("the list is full")
        }
        list.Tail++
        list.Length++
        list.Elemets[list.Tail] = elem
        return nil
    
    }
    
    func (list *Queue) pull() (string, error) {
        if list.Tail == -1 {
            return "", fmt.Errorf("the list is empty")
        }
    
        elem := list.Elemets[0]
        for i := 0; i < list.Tail; i++ {
            list.Elemets[i] = list.Elemets[i+1]
        }
        list.Elemets[list.Tail] = ""
        list.Tail--
        list.Length--
        return elem, nil
    
    }
    
    func main() {
        queue := NewQueue()
        queue.offer("AAAAA")
        queue.offer("BBBBB")
        fmt.Println(queue.pull())
        fmt.Println(queue.pull())
    
    }
原文地址:https://www.cnblogs.com/sxt102400/p/3234244.html