본문 바로가기

Computer Science/Data Structure

2. Queue (Linear Data Structure-FIFO)

https://www.geeksforgeeks.org/queue-data-structure/

public struct Queue<T> {

  fileprivate var array = [T?]()
  fileprivate var head = 0
  
  public var isEmpty: Bool {
    return count == 0
  }

  public var count: Int {
    return array.count - head // 앞쪽 시작점(Starting Point) = head
  }
  
  public mutating func enqueue(_ element: T) {
    array.append(element)
  }
  
  public mutating func dequeue() -> T? {
    guard head < array.count, let element = array[head] else { return nil }

    array[head] = nil
    head += 1

    let percentage = Double(head)/Double(array.count)
    if array.count > 50 && percentage > 0.25 { // 상황에 따라 비우는 기준 설정
      array.removeFirst(head) // k전까지 모두 삭제
      head = 0
    }
    
    return element
  }
  
  public var front: T? {
    if isEmpty {
      return nil
    } else {
      return array[head]
    }
  }
}

* LinkedList / Array로 구현 가능 (동적/정적)

- count  isEmpty  front

- enqueue  dequeue

Basic Operations of Queue Data Structure

  • Enqueue (Insert): Adds an element to the rear of the queue.
  • Dequeue (Delete): Removes and returns the element from the front of the queue.
  • Peek: Returns the element at the front of the queue without removing it.
  • Empty: Checks if the queue is empty.
  • Full: Checks if the queue is full.

Applications of Queue

  • Task scheduling in operating systems
  • Data transfer in network communication
  • Simulation of real-world systems (e.g., waiting lines)
  • Priority queues for event processing queues for event processing

[References]

https://github.com/kodecocodes/swift-algorithm-club/tree/master/Queue

https://www.geeksforgeeks.org/queue-data-structure/

'Computer Science > Data Structure' 카테고리의 다른 글

1. Stack (Linear Data Structure-LIFO)  (0) 2024.05.13
Data Structure & Algorithm Overview  (0) 2024.05.13