美文网首页数据结构和算法分析
数据结构之环形队列-> Swift 版本

数据结构之环形队列-> Swift 版本

作者: 大兵布莱恩特 | 来源:发表于2017-03-13 14:01 被阅读70次

    iOS 中的 NSOperationQueue 就是一种队列结构,遵循 FIFO 的原则,将 NSOperation 任务添加到队列中去,并挨个取出执行任务.

    Github代码地址 : https://github.com/ZhaoBingDong/DataStructure.git

    今天用 swift 代码来实现一个队列结构,使其具备一下特点
    1 能够插入一个新的元素到队列尾
    2 能够从队列头取出一个元素
    3 能够清空队列中的所有元素
    4 能够遍历队列中所有元素
    5 当队列为空或者满的时候不进行插入和取出的任何操作.

    一 : 创建一个队列

        init(capacity : Int) { // 构造函数创建出一个队列数据模型来
            queue_Capacity  = capacity
            self.clearQueue()
        }
        /// 清空队列
        open func clearQueue() {
        
            self.queue      =  [T]()
            queue_Length    = 0
            queue_Head      = 0
            queue_Tail      = 0
    
        }
    
    

    二 : 队列判断为空 或为满, 队列元素长度

        /// 获取队列元素的长度
        open func queueLength() -> Int {
            return queue_Length
        }
        
        /// 判断队列是否已经满了
        open func queueFull() -> Bool {
            return queue_Length == queue_Capacity
        }
        
        /// 判断队列是否为空
        open func queueEmpty() -> Bool {
            return queue_Length == 0;
        }
    
    

    三 : 入队列,在队列尾部位置插入一个元素

    
    /// 往队列中添加一个元素
        
        open func enQueue(_ element : String) -> Bool {
            if queueFull() {
                return false
            } else {
                self.queue?.insert(element, at: queue_Tail)
                queue_Tail+=1;
                queue_Tail = queue_Tail % queue_Capacity
                queue_Length+=1;
                return true
            }
        }
    
    

    四 : 出队列,在队列头部位置取出一个元素

    
        /// 从队列中取出来一个元素 如果队列为空 那么 取出来的为 nil
        
        open func deQueue() -> String? {
             if queueEmpty() {
                return nil
            } else {
                let element = self.queue?[queue_Head]
                queue_Head+=1;
                queue_Head = queue_Head % queue_Capacity
                queue_Length-=1;
                return element;
            }        
        }
    
    
    

    五 : 遍历队列中所有元素,检查队列插入 取出元素后的变化

         /// 遍历队列
        open func queueTraverse() {
            
            let total = queue_Length + queue_Head
            let start = queue_Head
          
            for i in start..<total {
               let sum = self.queue?[i%queue_Capacity]
                print("\n\(sum),\n")
            }
            
        }
    
    

    下边是代码结合 UI 展示队列插入 取出,清空的操作

    Untitled.gif

    相关文章

      网友评论

      本文标题:数据结构之环形队列-> Swift 版本

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