DATA STRUCTURES PROGRAM • QUEUES & DEQUES
Implement a Queue Using a Linked List
Learn how to implement a queue using a linked list using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Removed = 10 Front = 20
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <stdlib.h>
struct Node { int data; struct Node *next; };
struct Queue { struct Node *front; struct Node *rear; };
void enqueue(struct Queue *queue, int value)
{
struct Node *node = malloc(sizeof *node);
if (node == NULL) exit(EXIT_FAILURE);
node->data = value; node->next = NULL;
if (queue->rear == NULL) queue->front = node;
else queue->rear->next = node;
queue->rear = node;
}
int dequeue(struct Queue *queue)
{
if (queue->front == NULL) exit(EXIT_FAILURE);
struct Node *removed = queue->front; int value = removed->data;
queue->front = removed->next;
if (queue->front == NULL) queue->rear = NULL;
free(removed); return value;
}
int main(void)
{
struct Queue queue = {NULL, NULL};
enqueue(&queue, 10); enqueue(&queue, 20); enqueue(&queue, 30);
printf("Removed = %d\n", dequeue(&queue));
printf("Front = %d\n", queue.front->data);
while (queue.front != NULL) dequeue(&queue);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Removed = 10 Front = 20
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Insert through rear and remove through front, resetting rear when the final node leaves.
- Display the computed result.
Insert through rear and remove through front, resetting rear when the final node leaves.
EFFICIENCY
Time and space complexity
Time complexity
O(1) per operation
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
