0% found this document useful (0 votes)
13 views

Experiment no9

Dsa experiment

Uploaded by

divyathakran389
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Experiment no9

Dsa experiment

Uploaded by

divyathakran389
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Experiment no.

9
Aim: Write a program to understand the concept of queue using linked
list and its operations.
#include <stdio.h>
#include <stdlib.h>

#define MAX_CAPACITY 5

struct Node {
int data;
struct Node* next;
};

struct Queue {
struct Node* front;
struct Node* rear;
int size;
};

void enqueue(struct Queue* q, int item);


int dequeue(struct Queue* q);
void display(struct Queue* q);
int isEmpty(struct Queue* q);
int isFull(struct Queue* q);
int main() {
struct Queue q;
q.front = q.rear = NULL;
q.size = 0;

int choice, item;

do {
printf("\nQueue operation menu:\n");
printf("1. Enqueue (add item)\n");
printf("2. Dequeue (remove item)\n");
printf("3. Show Queue\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter the item to enqueue: ");
scanf("%d", &item);
enqueue(&q, item);
break;
case 2:
item = dequeue(&q);
if (item != -1) {
printf("Dequeued %d\n", item);
}
break;
case 3:
display(&q);
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice. Please reenter the choice between 1 to 4.\n");
}
} while (choice != 4);

return 0;
}

void enqueue(struct Queue* q, int item) {


if (isFull(q)) {
printf("Queue is full. Cannot enqueue %d.\n", item);
return;
}
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = item;
newNode->next = NULL;

if (q->rear == NULL) {
q->front = q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
q->size++;
printf("Enqueued %d\n", item);
}

int dequeue(struct Queue* q) {


if (isEmpty(q)) {
printf("Queue is empty.\n");
return -1;
}
struct Node* temp = q->front;
int item = temp->data;
q->front = q->front->next;

if (q->front == NULL) {
q->rear = NULL;
}

free(temp);
q->size--;
return item;
}

void display(struct Queue* q) {


if (isEmpty(q)) {
printf("Queue is empty.\n");
return;
}

struct Node* temp = q->front;


printf("Queue elements are: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

int isEmpty(struct Queue* q) {


return (q->front == NULL);
}

int isFull(struct Queue* q) {


return (q->size >= MAX_CAPACITY);
}
Output Experiment no. 9

You might also like