큐(Queue)

큐(Queue)λž€?

Queue

  • νλŠ” λ§€ν‘œμ†Œμ—μ„œ ν‘œλ₯Ό 사기 μœ„ν•΄μ„œ 쀄을 μ„œλŠ” κ²ƒμ²˜λŸΌ λ¨Όμ € λ“€μ–΄μ˜¨ 데이터가 λ¨Όμ € μ‚­μ œλ˜λŠ” ꡬ쑰이닀. 이런 μž…μΆœλ ₯ 방식을 FIFO(First In First Out)이라고 ν•œλ‹€.

큐 μΆ”μƒμžλ£Œν˜•(Queue Abstract Data Type)

  • IsFull(): 큐가 λ‹€ μ°Όμ„λ•Œ, trueλ₯Ό λ°˜ν™˜ν•œλ‹€.
  • IsEmpty(): 큐가 λΉ„μ–΄μžˆμ„λ•Œ, trueλ₯Ό λ°˜ν™˜ν•œλ‹€.
  • enqueue(): 큐의 끝에 item을 μΆ”κ°€ν•œλ‹€.
  • dequeue(): 큐의 맨 μ•žμ— item을 μ œκ±°ν•΄μ„œ λ°˜ν™˜ν•œλ‹€.
  • peek(): μŠ€νƒμ˜ 맨 μ•žμ— μ›μ†Œλ₯Ό μ œκ±°ν•˜μ§€ μ•Šκ³  λ°˜ν™˜ν•œλ‹€.

큐(Queue) μ•Œκ³ λ¦¬μ¦˜ (1)

  • νλŠ” μ—°κ²°λ¦¬μŠ€νŠΈ(Linked List)둜 κ΅¬ν˜„ν•  수 μžˆλ‹€. QueueLinkedList

    Node *Head, *Tail, *p, *q;
    
    enQ(Node *p){
      p <- Next = NULL;
      if(Tail != NULL){
          Tail -> Next = p;
          Tail = p;
      }
      else{
          Head = Tail = p;
      }
    }
    Node* deQ(){
      if(Head == NULL) return NULL;
      else{
          q = Head
          Head = Head -> Next
          return q;
      }
    }
    

    μ„ ν˜• 큐(Linear Queue)

  • μ„ ν˜• νλ‘œλ„ κ΅¬ν˜„ν•  수 μžˆλ‹€. ν•˜μ§€λ§Œ μ‚­μ œμ™€ μ‚½μž…μ„ λ°˜λ³΅ν•˜λ‹€λ³΄λ©΄ 계속 μ‚¬μš©ν•  수 μ—†λŠ” μΈλ±μŠ€κ°€ λ°œμƒν•˜κ²Œ λœλ‹€. 이것을 ν‘œλ₯˜(Drifting)ν˜„μƒμ΄λΌκ³  ν•œλ‹€.

    QueueDrifitng

μ›ν˜• 큐(Circular Queue)

  • 이것은 μ›ν˜• 큐λ₯Ό μ‚¬μš©ν•˜λ©΄ κ°„λ‹¨ν•˜κ²Œ ν•΄κ²° ν•  수 μžˆλ‹€.

    CircularQueue

  • μ›ν˜• νλŠ” μ‹€μ œλ‘œ μ›ν˜•μ΄ μ•„λ‹ˆλΌ μ„ ν˜• 큐λ₯Ό μ΄μš©ν•΄μ„œ κ΅¬ν˜„ν•œλ‹€.
  • μ΄ˆκΈ°κ°’ = Head = Tail = 0

    큐(Queue) μ•Œκ³ λ¦¬μ¦˜ (2)

    enQ(item){
      if(Full) return;
      Q[Tail] = item;
      Tail = (Tail + 1) % N;
    }
    deQ(){
      if(Empty) return;
      p = Q[Head];
      Head = (Head + 1) % N;
      return p;
    }
    
  • μ΄λ•Œ Full <-> Head == Tail, Empty <-> Head == Tailμ΄λΌλŠ” λ¬Έμ œκ°€ μžˆλ‹€.
  • 해결방법
    1. Counter λ„μž…
      • Full <-> Counter = N
      • Empty <-> Counter = 0
    2. Buffer(Q)λ₯Ό ν•œ μΉΈ 덜 μ‚¬μš©
      -> size N인 Q에 N-1κ°œκΉŒμ§€ μ±„μš°λ©΄ FULL둜 κ°„μ£Ό
      • Full <-> Head == (Tail+1) % N
      • Empty <-> Tail == Head
    3. Head, Tail의 μœ„μΉ˜μ •λ³΄λ₯Ό μœ μ§€ν•˜λ©΄μ„œ 값을 λ‹€λ₯΄κ²Œ ν•˜λŠ” 방법
      • Full <-> Out == (in % N) && in >= N
      • Empty <-> Out == (in % N) && in < N
      • μƒμ‚°μž/μ†ŒλΉ„μž 문제(Producer/Consumer problem)에 적용
       // Producer(μƒλŒ€μ μœΌλ‘œ Fast)
       while(1){
           produce an item
           while(Full); // busy loop으둜 Not Full 쑰건 νšλ“ν•΄μ•Ό 함
           B[in % N];
           in <- ((in + 1) % N) + N // N만큼 떨어진 곳에 μ €μž₯
       }
       // Consumer(μƒλŒ€μ μœΌλ‘œ Slow)
       while(1){
           while(Empty); // busy loop
           item <- B[out];
           out <- (out + 1) % N;
           in <- in % N // in < N
           return item;
       }