Q. Using array to execute the queue structure, write down an algorithm/program to
(i) Insert an element in the queue.
(ii) Delete an element from the queue.
Ans.
(i) Algorithm to Insert an element in the given queue.
QINSERT( QUEUE, N, FRONT, REAR, ITEM)
This method inserts an elements ITEM into a queue.
1. [QUEUE already filled ?]
if FRONT =1 and REAR =N or if FRONT = REAR +1 then
write:OVERFLOW, and Return.
2. [Find new value of REAR]
If FRONT : = NULL, then : [QUEUE initially empty]
Set FRONT : = 1 and REAR : = 1, Else if REAR = N then;
Set REAR : = 1
Else:
Set REAR : = REAR + 1 [End of if structure]
3.Set QUEUE [REAR]: = ITEM [This inserts new elements]
4. Return
(ii) Algorithm to erase an element from the Queue
QDELETE (QUEUE, N, FRONT, REAR, ITEM)
This method deletes an element from a Queue and assign it to the variable ITEM.
1. [Queue already Empty?]
If FRONT:= NULL, then write UNDERFLOW and Return
2. Set ITEM:=QUEUE[FRONT]
3. [Find new value of FRONT]
If FRONT=REAR, THEN[Queue has only one element to start.]
Set FRONT:=NULL and REAR:=NULL Else if FRONT=N then:
Set FRONT:=1
Else:
Set FRONT:=FRONT+1 [End of If structure]
4. Return.