Data Structures and AlgorithmsTU Board 2081
Define circular queue. How queue differ from stack. Write a program to implement linear queue.
10Answer
A circular queue is a queue in which the last position is connected back to the first, so the array is used in a circle. When rear reaches the end of the array it wraps round to index 0 if there is free space there.
It solves the main problem of a linear queue: in a linear queue, once rear reaches the end, the spaces freed at the front by deletions can never be reused. In a circular queue the positions move with rear = (rear + 1) % MAX and front = (front + 1) % MAX.
Queue vs stack
| Queue | Stack |
|---|---|
| FIFO: first in, first out | LIFO: last in, first out |
| Insert at the rear, delete from the front | Insert and delete at the same end, the top |
Two pointers: front and rear |
One pointer: top |
| Operations: enqueue, dequeue | Operations: push, pop |
| Example: printer queue, CPU scheduling | Example: function calls, undo, expression evaluation |
Program: linear queue using an array
#include <stdio.h>
#define MAX 5
int queue[MAX];
int front = -1, rear = -1;
void enqueue(int x) {
if (rear == MAX - 1) {
printf("Queue overflow\n");
return;
}
if (front == -1) front = 0; /* first element */
queue[++rear] = x;
printf("%d inserted\n", x);
}
void dequeue(void) {
if (front == -1 || front > rear) {
printf("Queue underflow\n");
return;
}
printf("%d deleted\n", queue[front++]);
}
void display(void) {
int i;
if (front == -1 || front > rear) {
printf("Queue is empty\n");
return;
}
for (i = front; i <= rear; i++)
printf("%d ", queue[i]);
printf("\n");
}
int main(void) {
enqueue(10); enqueue(20); enqueue(30);
display(); /* 10 20 30 */
dequeue(); /* 10 deleted */
display(); /* 20 30 */
return 0;
}
Discussion
Loading…
More Data Structures and Algorithms questions
What is AVL tree? How heap differ from tree? Construct an AVL tree for data 24,12,8,15,35,30,57,40,45 and 78.TU Board 208110Define list. How can you use linked list to implement stack? Explain circular linked list.TU Board 208110Explain big oh notation in brief. Find big oh of the following function: f(x) = 5x^4 + 9x^2 + 7x + 9.TU Board 20815Convert the infix expression A+(((B C) (D E)+F)/G)$(H I) into post expression using stack.TU Board 20815Write a program to find GCD of two numbers using recursion.TU Board 20815What is the application of spanning tree? Draw a MST of a graph containing any 8 vertices and 11 edges with arbitrary edge costs.TU Board 20815