1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swiftでキューを理解する

Posted at

キュー

スタックと逆でFIFOとなる構造体のことを言う。末尾に要素を入れることをエンキュー、先頭からでていくことをデキューと呼ばれる。お店の行列をイメージすればすっと入ってくる。

コード

どうぶつ.swift
//
public struct Queue<T> {
  fileprivate var array = [T]()

//数を返す
  public var count: Int {
    return array.count
  }

//アペンドで末尾に入れる(更新させるからmutating)
  public mutating func enqueue(_ element: T) {
    array.append(element)
  }

//空であればnil,先頭から取り除く (更新させるからmutating)
  public mutating func dequeue() -> T? {
    if isEmpty {
      return nil
    } else {
      return array.removeFirst()
    }
  }
//先頭の要素を返す
  public var front: T? {
    return array.first
  }
  public var end:T? {
    return array.last
}
}

var queueOfAnimals = Queue(array: ["🐺", "🐵", "🐑", "🐶", "🐍"])
//末尾に入れる
queueOfAnimals.enqueue("🐯")
//先頭を取り除く
queueOfAnimals.dequeue()

両端キュー

デックとも呼ばれる。キューと違い双方向から追加、削除が可能になる
EnqueueFront - 先頭に要素を挿入する
EnqueueBack - 末尾に要素を挿入する (キューのエンキューと同じ)
DequeueFront - 先頭にある要素を削除して返す (キューのデキューと同じ)
DequeueBack - 末尾にある要素を削除して返す

どうぶつ.swift

 //インサートに要素入れる(更新させるからmutating)
  public mutating func enqueueFront(_ element: T) {
    array.insert(element,at:0)
  }
// 最後要素を削除して返す。
public mutating func dequeueBack() -> T? {
    if isEmpty {
      return nil
    } else {
      return array.removeLast()
    }
  }
    
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?