ν(Queue)
ν(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)λ‘ κ΅¬νν μ μλ€.
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)νμμ΄λΌκ³ νλ€.
μν ν(Circular Queue)
-
μ΄κ²μ μν νλ₯Ό μ¬μ©νλ©΄ κ°λ¨νκ² ν΄κ²° ν μ μλ€.
- μν νλ μ€μ λ‘ μνμ΄ μλλΌ μ ν νλ₯Ό μ΄μ©ν΄μ ꡬννλ€.
- μ΄κΈ°κ° = 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μ΄λΌλ λ¬Έμ κ° μλ€.
- ν΄κ²°λ°©λ²
- Counter λμ
- Full <-> Counter = N
- Empty <-> Counter = 0
- Buffer(Q)λ₯Ό ν μΉΈ λ μ¬μ©
-> size NμΈ Qμ N-1κ°κΉμ§ μ±μ°λ©΄ FULLλ‘ κ°μ£Ό- Full <-> Head == (Tail+1) % N
- Empty <-> Tail == Head
- 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; }
- Counter λμ