DSA Lab 15 Program

 

Program for implementing dequeue.

#include <stdio.h>
#include <stdlib.h>
#define MAX 5 // Define maximum size of the deque
int deque[MAX];
int front = -1;
int rear = -1;
// Function to check if the deque is full
int isFull() {
    return ((front == 0 && rear == MAX - 1) || (front == rear + 1));
}
// Function to check if the deque is empty
int isEmpty() {
    return (front == -1);
}
// Function to insert an element at the front of the deque
void insertFront(int key) {
    if (isFull()) {
        printf("Overflow: Unable to insert element at the front.\n");
        return;
    }
    if (front == -1) { // First element insertion
        front = rear = 0;
    } else if (front == 0) {
        front = MAX - 1;
    } else {
        front = front - 1;
    }
    deque[front] = key;
}
// Function to insert an element at the rear of the deque
void insertRear(int key) {
    if (isFull()) {
        printf("Overflow: Unable to insert element at the rear.\n");
        return;
    }
    if (front == -1) { // First element insertion
        front = rear = 0;
    } else if (rear == MAX - 1) {
        rear = 0;
    } else {
        rear = rear + 1;
    }
    deque[rear] = key;
}
// Function to delete an element from the front of the deque
void deleteFront() {
    if (isEmpty()) {
        printf("Underflow: Unable to delete element from the front.\n");
        return;
    }
    if (front == rear) { // Only one element
        front = rear = -1;
    } else if (front == MAX - 1) {
        front = 0;
    } else {
        front = front + 1;
    }
}
// Function to delete an element from the rear of the deque
void deleteRear() {
    if (isEmpty()) {
        printf("Underflow: Unable to delete element from the rear.\n");
        return;
    }
    if (front == rear) { // Only one element
        front = rear = -1;
    } else if (rear == 0) {
        rear = MAX - 1;
    } else {
        rear = rear - 1;
    }
}
// Function to display the elements of the deque
void displayDeque() {
    if (isEmpty()) {
        printf("Deque is empty.\n");
        return;
    }
    printf("Elements in the deque are: ");
    int i = front;
    while (1) {
        printf("%d ", deque[i]);
        if (i == rear) break;
        i = (i + 1) % MAX;
    }
    printf("\n");
}
int main() {
    insertRear(5);
    insertRear(10);
    insertFront(15);
    insertFront(20);
    displayDeque();
    deleteFront();
    displayDeque();
    deleteRear();
    displayDeque();
    return 0;
} # Output Elements in the deque are: 20 15 5 10 Elements in the deque are: 15 5 10 Elements in the deque are: 15 5

Comments

Popular posts from this blog

Keyword , Identifier, Indentation, Comments & Documentation

DSA Lab 8 program

DSA Lab 7 Program