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())")