Data Structures
#Queues
Basic Operations on Queue Data Structure:
•Enqueue: Inserts an element in the queue through
rear pointer.
•Dequeue: Removes an element from the queue
through front pointer.
•Peek: Returns the front element of the queue.
•IsFull: Returns true is the queue is full otherwise
returns false.
•IsEmpty: Returns true is the queue is empty
otherwise returns false.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node *next;
};
case 2:
int main() { value = dequeue(&front, &rear);
struct Node* front = NULL; if (value != -1)
struct Node* rear = NULL; printf("%d dequeued from queue\n", value);
int choice, value; break;
while (1) { case 3:
printf("\n--- Queue Menu ---\n"); value = peek(front);
printf("1. Enqueue\n"); if (value != -1)
printf("2. Dequeue\n"); printf("Front element is %d\n", value);
printf("3. Peek\n"); break;
printf("4. Display Queue\n");
printf("5. Exit\n"); case 4:
printf("Enter your choice: "); printQueue(front);
scanf("%d", &choice); break;
switch (choice) { case 5:
case 1: printf("Exiting...\n");
printf("Enter the value to enqueue: "); exit(0);
scanf("%d", &value);
enqueue(&front, &rear, value); default:
break; printf("Invalid choice! Please enter a valid option.\n");
}
}
return 0;
}
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void enqueue(struct Node** front, struct Node** rear, int data) {
struct Node* newNode = createNode(data);
if (*rear == NULL) {
*front = *rear = newNode;
printf("%d enqueued to queue\n", data);
return;
}
(*rear)->next = newNode;
*rear = newNode;
printf("%d enqueued to queue\n", data);
}
int isEmpty(struct Node* front) {
return front == NULL;
}
int dequeue(struct Node** front, struct Node** rear) {
if (isEmpty(*front)) {
printf("Queue underflow\n");
return -1;
}
struct Node* temp = *front;
int dequeued = temp->data;
*front = (*front)->next;
if (*front == NULL) {
*rear = NULL;
}
free(temp);
return dequeued;
}
int peek(struct Node* front) {
if (isEmpty(front)) {
printf("Queue is empty\n");
return -1;
}
return front->data;
}
void printQueue(struct Node* front) {
if (isEmpty(front)) {
printf("Queue is empty\n");
return;
}
printf("Queue elements: ");
while (front != NULL) {
printf("%d ", front->data);
front = front->next;
}
printf("\n");
}
Thank You