Documente Academic
Documente Profesional
Documente Cultură
Implementation
FORMS OF QUEUES
Linear queues(simple queues)
Circular queues (queues as circular lists)
Priority queues
QUEUE WITH FIXED ARRAY SIZE
#define MAX 5
struct queue
{ int front=0, rear=-1;
int items[MAX];
}q ;
Full
if(q.rear==MAX-1) Full
Insert
if not Full
q.items[++q.rear]=x;
Empty
if(q.rear<q.front) Empty
Remove
If not Empty
x=q.items[q.front++];
DISADV. OF THIS APPROACH
When rear=front=last element, we can not add any new item
though the Q has some slots vacant.
Solution: On deletion, move all elements to the left by one
position and decrement rear by one.
Then we don’t need front indicator at all, because it is always 0
Modified version of delete()
if(q.rear==-1)
It is empty
x=q.items[0];
for(i=0;i<q.rear;i++)
q.items[i]=q.items[i+1];
q.rear--;
SHIFT()
#define MAX 5
struct queue
4 E q.rear=4 E
4
3 D D
3
2 C q.front=2 2 C q.front=2
1 1
0 0 F q.rear=0
q.item q.item
E q.front=4 q.front=4
4 E
3
2
1 G q.rear=1
0 F q.rear=0 F
CIRCULAR QUEUE OPERATIONS CONTINUED
q.item
G q.rear=1
F q.front=0
A 1 B 2 C 4
D 5 E 7 F 7 0
12/08/21 01:07
In an enqueue operation, when the array is
full, instead of throwing an exception, we can
Queues
replace the array with a larger one
Similar to what we did for an array-based
stack
The enqueue operation has amortized
running time
O(n) with the incremental strategy
O(1) with the doubling strategy
15