美文网首页
队列与循环队列

队列与循环队列

作者: Breezes | 来源:发表于2021-12-22 16:13 被阅读0次

    普通队列

    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
        }
    }
    

    循环队列

    普通队列会造成假溢出的问题,使用循环队列解决该问题,具体问题分析看这里
    leetcode 641. 设计循环双端队列

    class CircularDeque {
    
        public var capacity: Int
        private var deque: [Int]
        private var front: Int
        private var rear: Int
        
        init(_ k: Int) {
            capacity = k + 1 //牺牲一个空间,方便判断是否满队列 (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] //取尾部时,需要向后移动一下取,因为rear指针总是指向最后一个值的下一个指针
        }
        
        func isEmpty() -> Bool {
            return front == rear
        }
        
        func isFull() -> Bool {
            return (rear + 1) % capacity == front
        }
    }
    

    相关文章

      网友评论

          本文标题:队列与循环队列

          本文链接:https://www.haomeiwen.com/subject/dvbqqrtx.html