zoukankan      html  css  js  c++  java
  • 使用go语言创建一个简单的队列

    package main
    
    import "fmt"
    
    /*
      add        增加一个元索                     如果队列已满,则抛出一个IIIegaISlabEepeplian异常
      remove   移除并返回队列头部的元素    如果队列为空,则抛出一个NoSuchElementException异常
      element  返回队列头部的元素             如果队列为空,则抛出一个NoSuchElementException异常
      offer       添加一个元素并返回true       如果队列已满,则返回false
      poll         移除并返问队列头部的元素    如果队列为空,则返回null
      peek       返回队列头部的元素             如果队列为空,则返回null
      put         添加一个元素                      如果队列满,则阻塞
      take        移除并返回队列头部的元素     如果队列为空,则阻塞
     */
    type Queue struct {
    	maxSize int
    	array []interface{}
    	front int
    	rear int
    }
    
    //初始化队列
    func NewQueue(size int) *Queue {
    	if size < 1 {
    		size = 10 //设置默认值为10
    	}
    	return &Queue{
    		maxSize:size,
    		array:make([]interface{}, size),
    		front:-1,
    		rear:-1,
    	}
    }
    func main() {
    	queue := NewQueue(3)
    	queue.offer(1)
    	queue.offer(2)
    	queue.offer(3)
    	b := queue.offer(4)
    	fmt.Println(b)
    	fmt.Println(queue)
    	fmt.Println(queue.poll())
    	fmt.Println(queue.poll())
    	fmt.Println(queue.poll())
    	fmt.Println(queue.poll())
    	queue.offer(5)
    	queue.offer(6)
    	queue.offer(7)
    	b2 := queue.offer(8)
    	fmt.Println(b2)
    	fmt.Println(queue)
    	fmt.Println(queue.poll())
    	fmt.Println(queue.poll())
    	fmt.Println(queue.poll())
    	fmt.Println(queue.poll())
    }
    //添加数据在队列
    func (this *Queue) offer(val interface{}) bool {
    	//先判断队列是否满
    	if (this.rear - this.front) == this.maxSize {
    		return false
    	}
    	this.rear++
    	this.array[this.rear - this.front - 1] = val
    	return true
    }
    
    //返回队列头部元素并移除
    func (this *Queue) poll() interface{} {
    	//判断队列是否为空
    	if this.rear == this.front {
    		return nil
    	}
    	this.front++
    	var val  = this.array[this.front % this.maxSize]
    	this.array[this.front % this.maxSize] = nil
    	return val
    }
    
  • 相关阅读:
    python-json序列化和反序列化
    python-列表元祖字典集合、字符、字符串、函数处理
    Nmon监控服务端性能
    python-使用qq邮箱向163邮箱发送邮件、附件
    测试结论
    性能术语
    测试点-app、web、异常
    提测标准
    深度优先搜索的演示学习法——BlackBlank平台应用教学案例
    【赛后补题】ccpc2107秦皇岛H题
  • 原文地址:https://www.cnblogs.com/hirampeng/p/11220448.html
Copyright © 2011-2022 走看看