Skip to main content

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)

All Data Structure and Algorithm chapter 2 questions →