Queue
Queue
Queue
Data structure with First-In First-Out (FIFO) behavior
Queue
Data structure with First-In First-Out (FIFO) behavior
Out
In
B A
C B A
Typical Operations
on Queue REAR
Enqueue
7 6 5 4 3 2 1 0
ENQUEUE
Increment rear
#define MAXSIZE 100 (array index)
struct queue
{
int que[MAXSIZE];
int front,rear;
};
typedef struct queue QUEUE;
7 6 5 4 3 2 1 0
DEQUEUE
Increment front
(array index)
#define MAXSIZE 100
struct queue
{
int que[MAXSIZE];
int front,rear;
};
typedef struct queue QUEUE;
Rear FrontFront
7 6 5 4 3 2 1 0
Problem with Array implementation
The size of the queue depends on the number and order
of enqueue and dequeue.
It may be situation where memory is available but
enqueue is not possible.
ENQUEUE DEQUEUE
Effective queuing storage area of array gets reduced.
0 N
front
front rearrear
Use of circular array indexing
Possible Implementations
Linear Arrays:
Circular Arrays:
(static/dynamicaly allocated)
(static/dynamically allocated)
front rear
front
rear
[2] [5]
[1] [6]
[0] [7]
front=0
rear=0
Circular Queue
[3] [4] rear = 4
[3] [4]
C D
[2] [5]
[2] [5] B
After insertion
A
[1] [6] of A, B, C, D
[1] [6]
front=0
rear=0
Circular Queue
[3] [4] rear = 4
[3] [4]
C D
[2] [5]
[2] [5] B
After insertion
A
[1] [6] of A, B, C, D
[1] [6]
front=0
rear=0
After deletion of
[1] [6] of A, B
[0] [7]
front: index of queue-head (always empty – why?)
rear: index of last element, unless rear = front
[2] [5]
[2] [5]
ENQUEUE
front rear
QUEUE: Deletion from a Linked List
DEQUEUE
front rear
dequeue
create
QUEUE
isempty
size
QUEUE using Linked List
struct qnode{
int val;
struct qnode *next;
};
struct queue{
struct qnode *qfront, *qrear;
};
Direct applications
Waiting lists.
Access to shared resources (e.g., printer).
Multiprogramming.
Indirect applications
Auxiliary data structure for algorithms
Component of other data structures
Example 6: Print first N Fibonacci Numbers
using a Queue
rear front
1 0
Example 7: Use a Stack to reverse a Queue
30 -5 18 14 14 18 -5 30
rear front
14 18 -5 30
Example 8: Create a new Queue with given
elements appended at the end of the Queue in a
reverse order
30 -5 18 14
rear front
14 18 -5 30 30 -5 18 14
Example 9: Implement a Stack using a Queue
data structure
For a given stack create a same size array which you are
going to use as a Queue.
Push and pop operation of stack’s should be emulated with
the Enqueue and Dequeue operation.
You can use an intermediate Queue for the above
implementation.
Homework
• Implement a Priority Queue which maintains the
items in an order (ascending/ descending) and
has additional functions like remove_max and
remove_min