Queue implementation

rajendranjrf 2,841 views 14 slides Jul 04, 2015
Slide 1
Slide 1 of 14
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14

About This Presentation

Queue implementation


Slide Content

Queues

07/04/15 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()

07/04/15 CS 201
Sample Operation
Queue *Q;
enqueue(Q, “a”);
enqueue(Q, “b”);
enqueue(Q, “c”);
d=getFront(Q);
dequeue(Q);
enqueue(Q, “e”);
dequeue(Q);
q
front back
abce
d

07/04/15 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

}

07/04/15 CS 201
Implementation of Queue
(Linked List)
•Can use LinkedListItr as underlying implementation of Queues
a
1 a
2 a
3 a
4
head
tail
Queue
lst
LinkedList
addTail

07/04/15 CS 201
Code
struct Node {
int element;
Node * next;
};
struct QUEUE {
Node * front;
Node * rear;
};

07/04/15 CS 201
More code

More code
07/04/15 CS 201
CELL is a list node

07/04/15 CS 201
Implementation of Queue
(Array)
•use Array with front and back pointers as implementation of
queue
Queue
arr
0 1 7 8 923 4 5 6
ABCDEFG
front
back

07/04/15 CS 201
Circular Array
•To implement queue, it is best to view arrays as circular structure
0 1 7 8 923 4 5 6
ABCDEFG
front
back
front
back
A
B
C
D
EF
G
0
1
7
8
9
2
3
4
5
6
Circular view of arrays.

07/04/15 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

07/04/15 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
bcd
F
BBB
FF
BB
e

07/04/15 CS 201
Checking for Full/Empty State
What does (F==B) denote?
F
B
Queue
Empty
State
cde
B
F
f Queue
Full
State
size 0 size 4
cde
BF
Alternative - Leave a Deliberate Gap!
No need for size field.
Full Case : (adv(B)==F)

07/04/15 CS 201
Summary
•The definition of the queue operations
gives the ADT queue first-in, first-out
(FIFO) behavior
•The queue can be implemented by
linked lists or by arrays
•There are many applications
–Printer queues,
–Telecommunication queues,
–Simulations,
–Etc.
Tags