普通隊(duì)列
public class Queue<T> {
public var list: [T]
private var front: Int
private var rear: Int
private var size: Int
public init(_ count: Int) {
size = count+1
list = [T](repeating: 0 as! T, count: count)
front = 0
rear = 0
}
public func enQueue(item: T) {
if full() {
return
}
list[rear] = item
rear += 1
}
public func deQueue() -> T? {
if empty() {
return nil
}
let temp = list[front]
front += 1
return temp
}
public func empty() -> Bool {
return front == rear
}
public func full() -> Bool {
return rear == size-1
}
public func count() -> Int {
return rear - front
}
}
循環(huán)隊(duì)列
普通隊(duì)列會造成假溢出的問題亭姥,使用循環(huán)隊(duì)列解決該問題,具體問題分析看這里
leetcode 641. 設(shè)計(jì)循環(huán)雙端隊(duì)列
class CircularDeque {
public var capacity: Int
private var deque: [Int]
private var front: Int
private var rear: Int
init(_ k: Int) {
capacity = k + 1 //犧牲一個(gè)空間,方便判斷是否滿隊(duì)列 (rear + 1) % capacity = front
deque = [Int](repeating: 0, count: capacity)
front = 0
rear = 0
}
func insertFront(_ value: Int) -> Bool {
if isFull() {return false}
front = (front - 1 + capacity) % capacity
deque[front] = value
return true
}
func insertLast(_ value: Int) -> Bool {
if isFull() {return false}
rear = (rear + 1) % capacity
deque[rear] = value
return true
}
func deleteFront() -> Bool {
if isEmpty() {return false}
front = (front + 1) % capacity
return true
}
func deleteLast() -> Bool {
if isEmpty() {return false}
rear = (rear - 1 + capacity) % capacity
return true
}
func getFront() -> Int {
if isEmpty() {return -1}
return deque[front]
}
func getRear() -> Int {
if isEmpty() {return -1}
return deque[(rear - 1 + capacity) % capacity] //取尾部時(shí),需要向后移動一下取帮哈,因?yàn)閞ear指針總是指向最后一個(gè)值的下一個(gè)指針
}
func isEmpty() -> Bool {
return front == rear
}
func isFull() -> Bool {
return (rear + 1) % capacity == front
}
}