Docsity

Data Structures: Queues and Deques - A Comprehensive Guide with Examples, Exams of Data Structures and Algorithms

Partial preview of the text

Download Data Structures: Queues and Deques - A Comprehensive Guide with Examples and more Exams Data Structures and Algorithms in PDF only on Docsity!

QUEUES

Queues

  • (^) A linear list of elements
  • (^) Principle : FIFO (first in first out)
  • (^) Rule - Deletion from front and insertion at end
  • (^) Two pointers associated are:
    • (^) FRONT : contains location of front element of queue
    • (^) REAR : contains location of rear element of queue
  • (^) Two ways of representation:
    • (^) Arrays
    • (^) Linked List

Point to Remember

  • (^) To access an element from queue: Queue[Rear] ;

Queue[Front]

  • (^) Front=NULL or Rear=NULL // Queue is empty
  • (^) Whenever an element is deleted from a queue, Front is

increased by 1: Front:=Front+

  • (^) Whenever an element is added to a queue, Rear is

increased by 1: Rear:=Rear+

  • (^) Condition for queue is full for N elements??
  • (^) Queue contains only 1 element :
    • (^) Front=Rear

Example:

  • (^) Consider an empty queue of 5 locations and perform the

following operation on it : initially front:0 and rear:

  • (^) Insert A,B,C
  • (^) Del A
  • (^) D and E are inserted
  • (^) B and C are deleted
  • (^) Insert F
  • (^) D deleted
  • (^) G and H are inserted
  • (^) E deleted
  • (^) F deleted
  • (^) K inserted
  • (^) G and H are deleted
  • (^) K deleted
QINSERT(QUEUE,N,FRONT,REAR,ITEM)

This procedure inserts an element ITEM into a queue

  1. //[queue already filled?]

If FRONT=1 and REAR=N , or if FRONT=REAR+ Then: write OVERFLOW and return.

  1. // [find new value of REAR]

If FRONT:=NULL // [then queue initially empty]

Set FRONT:=1 and REAR:= Else if REAR=N , then : Set REAR:= Else: Set REAR:=REAR+ // [end of if structure]

  1. Set QUEUE[REAR]:=ITEM //[this inserts new element]

  2. RETURN

• QDELETE(QUEUE,N,FRONT,REAR,ITEM)

This procedure 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]

  1. //[find new value of FRONT]

if FRONT=REAR , then: //[queue has only one element] Set FRONT:=NULL and REAR:=NULL else if FRONT=N, then: set FRONT:= else set FRONT:=FRONT+ //[end of if structure]

  1. RETURN

LINKED REPRESENTATION[INSERT]

1. If AVAIL=NULL then write OVERFLOW and EXIT

2. Set NEW=AVAIL and AVAIL=LINK[AVAIL]

3. Set INFO[NEW]=ITEM and LINK[NEW]=NULL

4. If FRONT=NULL then FRONT=REAR=NEW

else set LINK[REAR]=NEW and REAR=NEW

5. Exit

LINKED REPRESENTATION[DELETE]

  1. If FRONT=NULL then write UNDERFLOW and EXIT
  2. Set TEMP=FRONT
  3. ITEM=INFO(TEMP)
  4. FRONT=LINK(TEMP)
  5. LINK(TEMP)=AVAIL and AVAIL=TEMP
  6. Exit

One-way representation of a Priority

queue

AA
A
START
BB
B
EEE 4 X
CCC 2
DDD 3