• 切片实现队列功能


    package main
    
    import (
        "fmt"
    )
    //队列:先进先出
    type Queue struct {
        StrArray []string
        Size     int
        Pos      int
    }
    
    func NewQueue(size int) *Queue {
        return &Queue{StrArray: make([]string, size), Size: size, Pos: -1}
    }
    
    //队尾push数据
    func (arr *Queue) RPush(item string) bool {
        if arr.IsFull() {
            return false
        }
        arr.Pos++
        arr.StrArray[arr.Pos] = item
        return true
    }
    
    //队头取出数据
    func (arr *Queue) LPop() (string, bool) {
        if arr.IsEmpty() {
            return "", false
        }
        item := arr.StrArray[0]
        for i := 1; i <= arr.Pos; i++  {
            arr.StrArray[i - 1] = arr.StrArray[i]
        }
        arr.Pos--
        return item, true
    }
    //判断是否空队列
    func (arr *Queue) IsEmpty() bool {
        return arr.Pos == -1
    }
    //判断是否满队列
    func (arr *Queue) IsFull() bool {
        return arr.Pos == arr.Size - 1
    }
    
    func main() {
        queue := NewQueue(5)
        queue.RPush("a")  
        queue.RPush("b")  
        queue.RPush("c")  
    
        fmt.Print(queue.StrArray) 
        fmt.Print(queue.LPop())   
    }
  • 相关阅读:
    @codeforces
    @总结
    @总结
    @codeforces
    @topcoder
    @codeforces
    @codeforces
    @codeforces
    @codeforces
    @codeforces
  • 原文地址:https://www.cnblogs.com/ashion89/p/13796562.html
Copyright © 2020-2023  润新知