torpedo87.github.io

Swift Algorithm Club: Swift Queue Data Structure

Swift Algorithm Club: Swift Queue Data Structure를 번역하였습니다.

시작하기

예제

queue.enqueue(10)
queue.enqueue(3)
queue.enqueue(57)
queue.dequeue()
queue.dequeue()

큐 구현하기

public struct Queue {

}

Enqueue

fileprivate var list = LinkedList<Int>()

public mutating func enqueue(_ element: Int) {
    list.append(element)
}

Dequeue

public mutating func dequeue() -> Int? {
    guard !list.isEmpty, let element = list.first else { return nil }

    list.remove(element)

    return element.value
}

Peek

func peek() -> Int? {

    return element.value
}

isEmpty

public var isEmpty: Bool {
    return list.isEmpty
}

큐 출력하기

var queue = Queue()
queue.enqueue(10)
queue.enqueue(3)
queue.enqueue(57)
print(queue)
Queue
extension Queue: CustomStringConvertible {
    public var description: String {
        return list.description
    }
}

"[10, 3, 57]"

제네릭 큐 구현하기

// 1
public struct Queue<T> {

  // 2
  fileprivate var list = LinkedList<T>()

  public var isEmpty: Bool {
    return list.isEmpty
  }
  
  // 3
  public mutating func enqueue(_ element: T) {
    list.append(element)
  }

  // 4
  public mutating func dequeue() -> T? {
    guard !list.isEmpty, let element = list.first else { return nil }

    list.remove(element)

    return element.value
  }

  // 5
  public func peek() -> T? {
    return list.first?.value
  }
}
var queue = Queue<Int>()
queue.enqueue(10)
queue.enqueue(3)
queue.enqueue(57)
var queue2 = Queue<String>()
queue2.enqueue("mad")
queue2.enqueue("lad")
if let first = queue2.dequeue() {
  print(first)
}
print(queue2)