美文网首页
swift写数据结构栈,队列

swift写数据结构栈,队列

作者: timeQuick | 来源:发表于2019-06-05 11:19 被阅读0次

栈是一种运算受限的线性表,它具有 后进先出(Last In First Out)的特性。仅能在线性表的一端操作,栈顶允许操作,栈底不允许操作。这种操作过程就有 入栈,出栈。

用数组的方式就能很简单的实现(主要是在数组的末端操作,如果在数组的首端操作会存在数组元素移动使时间复杂度O(n),而在数组末端操作O(1))

public struct Stack<T>{
    
    var array = [T]()
    
    //栈是否为空
    public var isEmpty:Bool{
        return array.isEmpty
    }
    
    //栈元素个数
    public var count:Int{
        return array.count
    }
    
    //入栈
    public mutating func push(_ element:T){
        return array.append(element)
    }
    
    //出栈
    public mutating func pop()->T? {
        return array.popLast()
    }
    
    //栈顶元素
    public var topElemet:T? {
        return array.last
    }
    
    //清栈
    public mutating func clearStack() {
        array.removeAll()
    }
}

队列
队列是FIFO 先进先出的特性,用数据的方法实现也很简单,这种简单的实现 dequeue的算法复杂库O(n),
The reason thatdequeue()andenqueueFront()are **O(n)** is that they work on the front of the array. If you remove an element at the front of an array, what happens is that all the remaining elements need to be shifted in memory.

public struct Deque<T> {
    var array = [T]()
    
    var isEmpty:Bool{
        return array.isEmpty
    }
    var count:Int {
        return array.count
    }
    //入队
    mutating func enqueue(element:T) {
        array.append(element)
    }
    //出队
    mutating func dequeue(element:T)  {
        array.removeFirst()
    }
    
    //拿到队列的 队头元素
    func getQueueFirstData() -> T? {
        return array.first
    }
    
    //队尾元素
    func getQueueLastData()->T?{
        return array.last
    }
}

换一种写法也可以把入队,出队的操作时间复杂度变为O(1),提高效率。
具体的详情有介绍 https://github.com/raywenderlich/swift-algorithm-club/blob/master/Queue/README.markdown

相关文章

  • swift写数据结构栈,队列

    栈是一种运算受限的线性表,它具有 后进先出(Last In First Out)的特性。仅能在线性表的一端操作,栈...

  • Algorithm小白入门 -- 队列和栈

    队列和栈队列实现栈、栈实现队列单调栈单调队列运用栈去重 1. 队列实现栈、栈实现队列 队列是一种先进先出的数据结构...

  • iOS开发集锦之 2017.03.30(Swift 算法实战之路

    1. Swift 算法实战之路:栈和队列 作者: 故胤道长描述:栈和队列的基本Swift实现,以及在iOS开发中应...

  • 栈和队列—什么是栈

    栈和队列是两种重要的数据结构 从数据结构角度看,栈和队列也是线性表,其特殊性在于栈和队列的基本操作是线性表操作的子...

  • 栈和队列—什么是队列

    栈和队列是两种重要的数据结构 从数据结构角度看,栈和队列也是线性表,其特殊性在于栈和队列的基本操作是线性表操作的子...

  • 泡杯茶,我们坐下聊聊javascript事件环

    栈和队列 在计算机内存中存取数据,基本的数据结构分为栈和队列。 栈(Stack)是一种后进先出的数据结构,注意,有...

  • 队列和栈的应用

    队列和栈的使用 标签(空格分隔): algorithm 队列和栈的应用 1.队列的应用 队列是一种常见的数据结构,...

  • 数据结构 栈和队列

    数据结构 栈和队列 栈 顺序栈 top = -1 链栈 初始化 判断队空 入队: 头插法 出队: 单链表删除 队列...

  • js数据结构-队列

    队列 上一篇数据结构讲到了栈,队列和栈非常类似。队列也是一种特殊的列表,它与栈的区别在于,栈是先入后出,而队列则是...

  • LeetCode 栈、队列、优先队列专题 1:栈和队列的使用

    这一部分,我们开始介绍“栈、队列、优先队列”。栈和队列虽然是简单的数据结构,但是使用这些简单的数据结构所解决的算法...

网友评论

      本文标题:swift写数据结构栈,队列

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