Queue implementation
-
Upload
rajendranjrf -
Category
Education
-
view
269 -
download
1
Transcript of Queue implementation
04/15/23 CS 201
Queue ADT
• Queues implement the FIFO (first-in first-out) policy– An example is the printer/job queue!
enqueue(o)dequeue()
isEmpty()getFront() createQueue()
04/15/23 CS 201
Sample OperationQueue *Q;
enqueue(Q, “a”);
enqueue(Q, “b”);
enqueue(Q, “c”);
d=getFront(Q);
dequeue(Q);
enqueue(Q, “e”);
dequeue(Q);
q
front back
a b c e
d
04/15/23 CS 201
Queue ADT interface
• The main functions in the Queue ADT are (Q is the queue)
void enqueue(o, Q) // insert o to back of Q void dequeue(Q); // remove oldest item Item getFront(Q); // retrieve oldest item boolean isEmpty(Q); // checks if Q is empty boolean isFull(Q); // checks if Q is full
void clear(Q); // make Q empty }
04/15/23 CS 201
Implementation of Queue (Linked List)
• Can use LinkedListItr as underlying implementation of Queues
a1 a2 a3 a4
head tail
Queue
lst
LinkedListaddTail
04/15/23 CS 201
Codestruct Node { int element; Node * next;};
struct QUEUE { Node * front; Node * rear;};
04/15/23 CS 201
Implementation of Queue (Array)
• use Array with front and back pointers as implementation of queue Queue
arr 0 1 7 8 92 3 4 5 6
A B C D E F G
frontback
04/15/23 CS 201
Circular Array• To implement queue, it is best to view arrays as circular structure
0 1 7 8 92 3 4 5 6
A B C D E F G
frontback
front
back
AB
C
DEF
G
0
1
7
8
9
2
3
456
Circular view of arrays.
04/15/23 CS 201
How to Advance
• Both front & back pointers should make advancement until they reach end of the array. Then, they should re-point to beginning of the array
front = adv(front);back = adv(back);
int adv(int p) { return ((p+1) % maxsize); }
Alternatively, use modular arithmetic:
mod operator
int adv(int p) { int r = p+1; if (r<maxsize) return r; else return 0; }
upper bound of the array
04/15/23 CS 201
Sample
Queue *Q;
enqueue(Q, “a”);
enqueue(Q, “b”);
enqueue(Q, “c”);
dequeue(Q);
dequeue(Q);
enqueue(Q, “d”);
enqueue(Q, “e”);
dequeue(Q);
a
Q
F=front B=back
F
B
b c d
F
B B B
F F
B B
e
04/15/23 CS 201
Checking for Full/Empty State
What does (F==B) denote?
FB
QueueEmptyState
c de
B
F
f QueueFullState
size 0 size 4
c de
B F
Alternative - Leave a Deliberate Gap!
No need for size field.
Full Case : (adv(B)==F)