This is the 13th day of my participation in Gwen Challenge

How to understand “queue”?

The main feature of a Queue is first in, first out. The two main operations are Queue entry and Queue exit. Like a stack, it can be implemented as an array or a linked list. Arrays are called sequential queues, and linked lists are called linked queues.

In many algorithms, we want to add items to the temporary list at some point and then pull them out of the list again at a later time. The order in which these items are added and removed is very important.

Give me a chestnut

Think of it as queuing to buy a ticket. Those who come first buy first, and those who come later can only stand at the end and are not allowed to jump the queue. First come first, this is a typical “*** queue ***”.

The stack supports only two basic operations: push()** and pop() **. Queues are very similar to stacks in that they support very limited operations. The most basic operations are also two: enqueue(), put a data to the end of the queue; Dequeue () takes an element from the head of the queue.

Implement queues with swift arrays

Here are a few things to know about iOS queues:

  • The queue is a first-in, first-out structure
  • The multi-threaded GCD and NSOperationQueue in iOS development are implemented based on queues.
  • Focus on the following operations for queues: enqueue, dequeue, isEmpty, peek, size.

public struct Queue<T> {
  
    fileprivate var list = LinkedList<T> ()/ / team
    public mutating func enqueue(_ element: T) {
        list.append(element)
    }
  
  	/ / out of the team
    public mutating func dequeque(a) -> T? {

        guard !list.isEmpty, let element = list.first else { return nil}
        
        list.remove(element)
        
        return element.value
    }
  
  	/ / check
    public func peek(a) -> T? {
        return list.first?.value
    }
    
    public var isEmpty: Bool {
        return list.isEmpty
    }
}
Copy the code

Let’s review yesterday’s Stack

struct Stack<Element> {
    fileprivate var array:[Element] = []
    / / into the stack
    mutating func push(_ element:Element) {
        array.append(element)
    }
    / / out of the stack
    mutating func pop(a)-> Element? {
        return array.popLast()
    }
    / / check
    func peek(a)-> Element? {
        return array.last
    }
}
Copy the code

reference

www.raywenderlich.com/848-swift-a…

Segmentfault.com/a/119000001…

Blog.csdn.net/zhangjitao_…