Data Structures
Topic: Queue
Lovely Professional University, Punjab
Outlines
Introduction
Examples of Queues
Application of Queues
Basic Operations on Queue
Representation of Queues
Array Representation
Linked Representation
Priority Queues
Review Questions
Introduction
A Queue is a linear list of elements in which deletions can take
place only at one end, called the ‘FRONT’ and insertions can
take place only at the other end, called the ‘REAR’.
Queues are also called as FIFO list.
Array
Representation
Work Space
Insertion into a Queue
Q_INSERT (QUEUE, N, FRONT, REAR, ITEM)
1. If FRONT = 1 and REAR = N, or If FRONT = REAR+1, then:
Write: OVERFLOW and Return. [Overflow]
2. If FRONT = 0, 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.
4. Return.
Deletion in a Queue
Q_DELETE (QUEUE, N, FRONT, REAR, ITEM)
1. If FRONT = 0, then:
Write: UNDERFLOW and Return. [Underflow]
2. Set ITEM = QUEUE [FRONT].
3. If FRONT = REAR, then [Queue has only one element]
Set FRONT = 0 and REAR = 0.
Else if FRONT = N, then:
Set FRONT = 1.
Else:
Set FRONT = FRONT + 1.
[End of if Structure.]
4. Return.
LINKED
Representation
Work Space
Insertion into a Queue
LINK_Q_INSERT (INFO, LINK, FRONT, REAR, AVAIL, ITEM)
1. [Available space?] 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
Deletion in a Queue
LINK_Q_DELETE (INFO, LINK, FRONT, REAR, AVAIL, ITEM)
1. [Queue Empty?] If FRONT = NULL, then:
Write “UNDERFLOW” and Exit.
2. Set TEMP = FRONT.
3. Set ITEM = INFO [TEMP].
4. IF: FRONT = REAR THEN: Set FRONT = NULL and REAR = NULL
5. ELSE: Set FRONT = LINK [FRONT]
6. Set LINK [TEMP] = AVAIL and AVAIL = TEMP.
7. Exit
Deques
Deque (aka Double-ended queue) is a linear list in which
elements can be added or removed at either end but not in the
middle.
Deques are represented using circular array. Thus DEQUE[1]
comes after DEQUE[N]
Two variations of Deque are:
1. Input-restricted deque
2. Output-restricted deque
Variations of Deque
Input-Restricted Deque:
allows insertion only at one end while deletion in both ends of
the list.
Output-Restricted Deque:
allows deletion only at one end while insertion at both the ends
of the list.
Work Space
Priority Queue
A Priority Queue is a collection of elements such that each
element has been assigned a priority and such that the order in
which elements are processed comes from the following rules:
o An element of higher priority is processed before any element of
lower priority.
o Two elements with the same priority are processed according to
the order in which they were added to the queue.
Example
Time sharing systems: Programs of high priority are processed
first.