- Asked 2/14
- 2073 Magh · 6 marks
- 2071 Magh · 6 marks
Linear queue using array
Short answer
A linear queue uses an array with front and rear indices. Initialize front=0, rear=-1. Insert increments rear and stores; remove increments front. Overflow when rear==MAX-1, underflow when front>rear. Main drawback: wasted space after deletions.
Implement a linear queue as a list by using static (array) implementation. Write pseudo code for this implementation.
A linear queue can be stored in an array with two integer indices, front and rear.
Structure
#define MAX 100
struct queue {
int items[MAX];
int front, rear;
};
Pseudo code
Initialize(q): q.front = 0; q.rear = -1
Empty(q): return (q.front > q.rear) /* TRUE if no element */
Full(q): return (q.rear == MAX - 1)
Insert(q, x): /* enqueue */
1. if Full(q): print "Queue overflow"; return
2. q.rear = q.rear + 1
3. q.items[q.rear] = x
Remove(q): /* dequeue */
1. if Empty(q): print "Queue underflow"; return ERROR
2. x = q.items[q.front]
3. q.front = q.front + 1
4. return x
Display(q):
for i = q.front to q.rear: print q.items[i]
C implementation
#include <stdio.h>
#define MAX 5
struct queue { int items[MAX]; int front, rear; };
void init(struct queue *q) { q->front = 0; q->rear = -1; }
int empty(struct queue *q) { return q->front > q->rear; }
int full(struct queue *q) { return q->rear == MAX - 1; }
void insert(struct queue *q, int x) {
if (full(q)) { printf("Queue overflow\n"); return; }
q->items[++q->rear] = x;
}
int removeq(struct queue *q) {
if (empty(q)) { printf("Queue underflow\n"); return -1; }
return q->items[q->front++];
}
Note: after many deletions rear may reach MAX - 1 while the front part is free; this wasted space is the main weakness of the linear queue (a circular queue removes it).
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Dynamic implementation of queue · Data Structure and Algorithm, chapter 4
- Array list; static or dynamic choice · Data Structure and Algorithm, chapter 3
- Static and dynamic data structures; array list · Data Structure and Algorithm, chapter 3
- Array implementation of list in C · Data Structure and Algorithm, chapter 3
- Circular queue vs linear queue · Data Structure and Algorithm, chapter 2
- Linear and circular queue operations · Data Structure and Algorithm, chapter 2
- Algorithm/pseudo-code for software PID · Embedded System, chapter 7 · asked 3×
- Gauss-Jordan pseudo-code · Numerical Method, chapter 3 · asked 4×
- Bisection method pseudo-code · Numerical Method, chapter 2 · asked 3×
- False position pseudo-code · Numerical Method, chapter 2 · asked 2×