@cxm-2016
2016-12-15T10:25:34.000000Z
字数 1159
阅读 1427
数据结构
版本:1
作者:陈小默
声明:禁止商用,禁止转载
设计一个队列结构,要求使用数组实现循环队列
/**
* Copyright (C) <2016> <陈小默>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Created by 陈小默 on 11/06.
*/
class Queue<E>(val max: Int) {
val queue = Array<Any?>(max, { null })
private var head = 0
private var tail = 0
var size = 0
private set
val isEmpty: Boolean get() = size == 0
val isFull: Boolean get() = size == max
/**
* 添加数据到队列尾
*/
fun add(e: E): Boolean {
if (isFull)
return false
queue[tail] = e
if (++tail >= max) tail = 0
size++
return true
}
/**
* 移除队列头数据
*/
fun poll(): E {
if (isEmpty) throw RuntimeException("queue is empty")
val value = queue[head] as E
queue[head] = null
if (++head >= max) head = 0
size--
return value
}
/**
* 获取但不移除队列头数据
*/
fun peek(): E {
if (isEmpty) throw RuntimeException("queue is empty")
return queue[head] as E
}
}