This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
/**
*File:array_queue.swift
*CreatedTime:2023-01-11
*Author:nuomi1(nuomi1@qq.com)
*/
/*基于环形数组实现的队列*/
classArrayQueue{
privatevarnums:[Int]//用于存储队列元素的数组
privatevarfront:Int//队首指针,指向队首元素
privatevar_size:Int//队列长度
init(capacity:Int){
//初始化数组
nums=Array(repeating:0,count:capacity)
front=0
_size=0
}
/*获取队列的容量*/
funccapacity()->Int{
nums.count
}
/*获取队列的长度*/
funcsize()->Int{
_size
}
/*判断队列是否为空*/
funcisEmpty()->Bool{
size()==0
}
/*入队*/
funcpush(num:Int){
ifsize()==capacity(){
print("队列已满")
return
}
//计算队尾指针,指向队尾索引+1
//通过取余操作实现rear越过数组尾部后回到头部
letrear=(front+size())%capacity()
//将num添加至队尾
nums[rear]=num
_size+=1
}
/*出队*/
@discardableResult
funcpop()->Int{
letnum=peek()
//队首指针向后移动一位,若越过尾部,则返回到数组头部
front=(front+1)%capacity()
_size-=1
returnnum
}
/*访问队首元素*/
funcpeek()->Int{
ifisEmpty(){
fatalError("队列为空")
}
returnnums[front]
}
/*返回数组*/
functoArray()->[Int]{
//仅转换有效长度范围内的列表元素
(front..<front+size()).map{nums[$0%capacity()]}
}
}
@main
enum_ArrayQueue{
/*DriverCode*/
staticfuncmain(){
/*初始化队列*/
letcapacity=10
letqueue=ArrayQueue(capacity:capacity)
/*元素入队*/
queue.push(num:1)
queue.push(num:3)
queue.push(num:2)
queue.push(num:5)
queue.push(num:4)
print("队列 queue = \(queue.toArray())")
/*访问队首元素*/
letpeek=queue.peek()
print("队首元素 peek = \(peek)")
/*元素出队*/
letpop=queue.pop()
print("出队元素 pop = \(pop),出队后 queue = \(queue.toArray())")