3 Queue

Data Structures and Algorithms · Unit 3 · 4 hrs

Queue

Exam-focused notes for Queue (Data Structures and Algorithms, CSC211): what the TU syllabus asks and how it has actually been tested, with 8 solved past questions from this unit.

Queue in short

This chapter introduces the queue, the other fundamental restricted access linear structure, its array based linear and circular implementations, the priority queue, and the double ended queue (dequeue).

Queue: notes

Basic Concept of Queue, Queue as an ADT, Primitive Operations in Queue

A queue is a linear data structure in which insertion happens at one end, called the rear, and deletion happens at the other end, called the front. It follows the First In First Out (FIFO) discipline: the element inserted first is the first one removed, like a line of people waiting to be served. As an ADT, a queue $q$ of type $T$ supports:

  • MakeEmpty(q): create an empty queue.
  • Enqueue(q, x): insert x at the rear, provided q is not full.
  • Dequeue(q): remove and return the element at the front, provided q is not empty.
  • IsEmpty(q) / IsFull(q): report whether q is empty or full.
  • Traverse(q): visit every element of q from front to rear.

Queues appear wherever tasks must be served in arrival order: jobs waiting to print, processes waiting for the CPU in a time sharing operating system, requests waiting for disk access, and task scheduling generally.

What this unit covers

  • Basic Concept of Queue, Queue as an ADT, Primitive Operations in Queue
  • Linear Queue, Circular Queue, Priority Queue, Queue Applications

Linear Queue, Circular Queue, Priority Queue, Queue Applications

2081 · 10 marks

Define circular queue. How queue differ from stack. Write a program to implement linear queue.[10]

Show solved answer

Circular Queue, Queue vs Stack, and Linear Queue Implementation


1. Definition of Circular Queue (2 marks)

A circular queue is a linear data structure that arranges data elements in a circular pattern, where the last element is connected back to the first element. It overcomes the major drawback of a linear queue (wastage of memory space).

In a circular queue:

  • Insertion and deletion follow the FIFO (First-In-First-Out) principle.
  • When the rear pointer reaches the end of the array, it wraps around to the beginning (index 0), reusing the freed spaces.
  • This eliminates the problem where storage space at the beginning of the array is discarded and never used again (as happens in a linear queue).

Condition:

  • Queue is empty when front == -1
  • Queue is full when (rear + 1) % SIZE == front

2. Differences Between Queue and Stack (3 marks)

FeatureQueueStack
PrincipleFollows FIFO (First-In-First-Out)Follows LIFO (Last-In-First-Out)
Insertion EndInsertion is done at the rear endInsertion (PUSH) is done at the top
Deletion EndDeletion is done at the front endDeletion (POP) is done at the top
Pointers UsedUses two pointers: front and rearUses one pointer: top
OperationsCalled Enqueue (insert) and Dequeue (delete)Called PUSH (insert) and POP (delete)
AccessOnly the front element is accessible for removalOnly the top element is accessible
Example UseCPU scheduling, printer spoolingFunction call management, expression evaluation

As stated in the notes: "The stack works as LIFO (last-in-first-out) technique but the queue works as FIFO technique (first-in-first-out) i.e., the first element inserted into the queue is the first element to be removed."


3. Program to Implement Linear Queue (5 marks)

A linear queue is an ordered collection where:

  • Elements are inserted at the rear end.
  • Elements are deleted from the front end.
  • It follows the FIFO principle.

Note: The main problem with linear queue is that both rear and front indices are increased but never decreased, leading to wastage of storage space.

#include <stdio.h>
#include <stdlib.h>

#define SIZE 5   /* Maximum size of the queue */

int queue[SIZE];
int front = -1;
int rear  = -1;

/* ---- Function to check if queue is empty ---- */
int isEmpty()
{
    if (front == -1 || front > rear)
        return 1;
    return 0;
}

/* ---- Function to check if queue is full ---- */
int isFull()
{
    if (rear == SIZE - 1)
        return 1;
    return 0;
}

/* ---- Enqueue: Insert element at rear ---- */
void enqueue(int value)
{
    if (isFull())
    {
        printf("Queue Overflow! Cannot insert %d\n", value);
        return;
    }
    if (front == -1)
        front = 0;   /* First element being inserted */

    rear = rear + 1;
    queue[rear] = value;
    printf("Inserted: %d\n", value);
}

/* ---- Dequeue: Delete element from front ---- */
void dequeue()
{
    if (isEmpty())
    {
        printf("Queue Underflow! Queue is empty.\n");
        return;
    }
    printf("Deleted: %d\n", queue[front]);
    front = front + 1;

    /* Reset queue when all elements are removed */
    if (front > rear)
    {
        front = -1;
        rear  = -1;
    }
}

/* ---- Display all elements in the queue ---- */
void display()
{
    int i;
    if (isEmpty())
    {
        printf("Queue is empty.\n");
        return;
    }
    printf("Queue elements (front to rear): ");
    for (i = front; i <= rear; i++)
    {
        printf("%d  ", queue[i]);
    }
    printf("\n");
}

/* ---- Main Function ---- */
int main()
{
    int choice, value;

    printf("=== Linear Queue Implementation ===\n");

    do {
        printf("\n1. Enqueue (Insert)");
        printf("\n2. Dequeue (Delete)");
        printf("\n3. Display");
        printf("\n4. Exit");
        printf("\nEnter your choice: ");
        scanf("%d", &choice);

        switch (choice)
        {
            case 1:
                printf("Enter value to insert: ");
                scanf("%d", &value);
                enqueue(value);
                break;
            case 2:
                dequeue();
                break;
            case 3:
                display();
                break;
            case 4:
                printf("Exiting...\n");
                break;
            default:
                printf("Invalid choice!\n");
        }
    } while (choice != 4);

    return 0;
}

Sample Output

=== Linear Queue Implementation ===

1. Enqueue (Insert)
2. Dequeue (Delete)
3. Display
4. Exit
Enter your choice: 1
Enter value to insert: 10
Inserted: 10

Enter your choice: 1
Enter value to insert: 20
Inserted: 20

Enter your choice: 1
Enter value to insert: 30
Inserted: 30

Enter your choice: 3
Queue elements (front to rear): 10  20  30

Enter your choice: 2
Deleted: 10

Enter your choice: 3
Queue elements (front to rear): 20  30

Enter your choice: 4
Exiting...

4. Limitation of This Linear Queue

Once rear reaches SIZE - 1, isFull() reports the queue as full even if elements have already been dequeued from the front and slots 0 to front-1 are sitting empty, because rear and front only ever move forward and are never wrapped back to the start of the array. This wasted space is exactly the drawback that the circular queue (Section 1) fixes, by wrapping rear and front around to index 0 with the modulo operation once the array end is reached, so the same allocated storage can be reused indefinitely instead of being abandoned after one pass through the array.

Open this answer on its own page →

2081 · 5 marks

What is linear queue? Why do we need circular queue? Explain. [5]

A linear queue is a linear data structure that follows the FIFO (First In First Out) principle, where: - Elements are inserted from the REAR end - Elements are deleted from the FRONT end In an array-based linear queue, two pointers are maintained: - FRONT: points to the first element - REAR: poin...

Open this answer on its own page →

2079 · 5 marks

Define queue. Explain about enqueue and dequeue operation in circular queue. [5]

A queue is a linear data structure that follows the FIFO (First In First Out) principle, meaning the element inserted first is the one deleted first. Elements are inserted at the rear end and deleted from the front end. Common operations on a queue include: - Enqueue(q, x): Insert item x at the r...

Open this answer on its own page →

2079 · 5 marks

Write short notes on: a. Priority Queue b. Breadth First traversal of a graph [5]

--- A priority queue is a collection of elements in which each element has been assigned a priority value, and the order of deletion and processing is governed by the following rules: 1. An element of higher priority is processed before any element of lower priority. 2. If two elements have the s...

Open this answer on its own page →

2078 · 5 marks

What is priority queue? Why do you need this type of queue? [5]

A priority queue is a special type of queue in which each element is assigned a priority value, and elements are processed (removed) according to their priority rather than their order of insertion (i.e., not strictly FIFO). - In an ascending priority queue, the element with the minimum (smallest...

Open this answer on its own page →

Basic Concept of Queue, Queue as an ADT, Primitive Operations in Queue

2080 · 10 marks

Explain queue as an ADT. Write a program to implement linear queue. Compare linear queue with circular queue.[10]

--- A Queue is a linear data structure that follows the FIFO (First In First Out) principle, meaning the element inserted first is the one removed first. It is analogous to a real-life queue (e.g., people standing in a line). A Queue ADT defines a data structure in terms of: - Data: An ordered co...

Open this answer on its own page →

2078 · 10 marks

Define Queue. Write are different applications of queue? Explain queue operations with example.[10]

Show solved answer

Queue: Definition, Applications, and Operations

1. Definition of Queue

A Queue is a linear data structure that follows the FIFO (First In First Out) principle, meaning the element inserted first is the element removed first. It is an ordered collection of elements in which insertion takes place at one end called the REAR and deletion takes place at the other end called the FRONT.

A queue can be compared to a real-life queue of people standing in a line -- the person who joins first gets served first.

FRONT                          REAR
  |                              |
  v                              v
[ 10 | 20 | 30 | 40 | 50 ]
  ^                              ^
(Deletion side)          (Insertion side)

2. Applications of Queue

Queues are widely used in computer science and real-life scenarios:

#ApplicationDescription
1CPU SchedulingProcesses are scheduled for CPU execution in a queue (Round Robin, FCFS)
2Printer SpoolingPrint jobs are queued and processed one by one in order
3Keyboard BufferKeystrokes are stored in a queue and processed in order
4BFS (Breadth First Search)Graph traversal uses a queue to visit nodes level by level
5IO BuffersData transfer between processes uses queues as buffers
6SimulationQueues model real-world waiting lines (bank, ticket counter)
7Network Packet HandlingData packets are queued for transmission over a network
8Operating SystemJob scheduling, interrupt handling use queues

3. Queue Operations

The primary operations performed on a queue are:

3.1 Basic Operations

OperationDescription
Enqueue (Insert)Add an element at the REAR of the queue
Dequeue (Delete)Remove an element from the FRONT of the queue
IsEmptyCheck whether the queue is empty
IsFullCheck whether the queue is full
Peek / FrontReturn the front element without removing it

3.2 Queue Declaration (Array-based)

#define MAXSIZE 5

struct queue {
    int items[MAXSIZE];
    int front;
    int rear;
};
typedef struct queue Q;
  • Initially: front = -1, rear = -1

3.3 IsEmpty Operation

int IsEmpty(Q *q) {
    if (q->front == -1)
        return 1;   // Queue is empty
    else
        return 0;
}

3.4 IsFull Operation

int IsFull(Q *q) {
    if (q->rear == MAXSIZE - 1)
        return 1;   // Queue is full
    else
        return 0;
}

3.5 Enqueue Operation

Algorithm:

  1. Check if queue is full. If full, print overflow and exit.
  2. If queue is empty, set front = 0.
  3. Increment rear by 1.
  4. Insert the new element at items[rear].
void Enqueue(Q *q, int newitem) {
    if (IsFull(q)) {
        printf("Queue Overflow! Cannot insert.");
        return;
    }
    if (IsEmpty(q))
        q->front = 0;
    q->rear = q->rear + 1;
    q->items[q->rear] = newitem;
    printf("%d inserted into queue.\n", newitem);
}

3.6 Dequeue Operation

Algorithm:

  1. Check if queue is empty. If empty, print underflow and exit.
  2. Store the front element.
  3. If front == rear, reset both to -1 (queue becomes empty).
  4. Otherwise, increment front by 1.
  5. Return the stored element.
int Dequeue(Q *q) {
    int val;
    if (IsEmpty(q)) {
        printf("Queue Underflow! Cannot delete.");
        return -1;
    }
    val = q->items[q->front];
    if (q->front == q->rear)
        q->front = q->rear = -1;
    else
        q->front = q->front + 1;
    return val;
}

4. Worked Example

Perform the following operations on a queue of size 5: Enqueue(10), Enqueue(20), Enqueue(30), Dequeue(), Enqueue(40), Dequeue()

Step-by-step Trace:

Initial State:

front = -1,  rear = -1
Queue: [  |  |  |  |  ]

Step 1: Enqueue(10)

front = 0,  rear = 0
Queue: [ 10 |  |  |  |  ]

Step 2: Enqueue(20)

front = 0,  rear = 1
Queue: [ 10 | 20 |  |  |  ]

Step 3: Enqueue(30)

front = 0,  rear = 2
Queue: [ 10 | 20 | 30 |  |  ]

Step 4: Dequeue() --> returns 10

front = 1,  rear = 2
Queue: [  | 20 | 30 |  |  ]

Step 5: Enqueue(40)

front = 1,  rear = 3
Queue: [  | 20 | 30 | 40 |  ]

Step 6: Dequeue() --> returns 20

front = 2,  rear = 3
Queue: [  |  | 30 | 40 |  ]

Final State: front = 2, rear = 3, containing 30 and 40 in the queue.


Conclusion

The queue correctly follows FIFO order throughout this trace: the elements 10 and then 20 were removed in the same order they were inserted, and the two remaining elements, 30 and 40, stay in the array between the current front and rear indices, ready to be dequeued in that same order. This worked example, together with the array-based structure and the Enqueue/Dequeue/IsEmpty/IsFull operations defined above, completes the description of the queue data structure and its uses.

Open this answer on its own page →

2077 · 5 marks

Explain queue as an ADT. [5]

A queue is an ordered collection of items from which items may be deleted at one end (called the front) and into which items may be inserted at the other end (called the rear). A queue follows the FIFO (First-In-First-Out) principle, meaning the first element inserted into the queue is the first ...

Open this answer on its own page →