Latest

6/recent/ticker-posts

Write a program in c to insert an element in the middle and delete the middle element of queue

 #include<stdio.h>

#include<stdlib.h>

int rear =0;

int front =0;

int queue[100];

void enqueue(int data)

{


if (100== rear) {

printf("ERROR\n");

return;

}

else {

queue[rear] = data;

rear++;

}

return;

}

void dequeue()

{


if (front == rear) {

printf("ERROR\n");

return;

}


else {

for (int i = 0; i < rear - 1; i++) {

queue[i] = queue[i + 1];

}


rear--;

}

return;

}


void display()

{

int i;

printf("Queue elements are:\n");

if (front == rear) {

printf("EMPTY\n");

return;

}

for (i = front; i < rear; i++) {

printf("%d  ", queue[i]);

}

printf("\n");

return;

}

void qfront()

{

if (front == rear) {

printf("\nEmpty\n");

return;

}

printf("Front Element is: %d", queue[front]);

printf("\n");

return;

}

void insertmiddle(int data)

{

    int p=rear/2;

    int temp=queue[rear-1];

    for(int i=p+1;i<rear;i++)

    {

        queue[i]=queue[i-1];

    }

    queue[p]=data;

    rear++;

    queue[rear-1]=temp;

}

void deletemiddle()

{

    int p=rear/2;

    for(int i=p;i<rear-1;i++)

    {

       queue[i]=queue[i+1] ;

    }

    rear--;

}

int main()

{


    printf("What you want to perform, 1: to insert at front, 2: to delete from front, 3: to return the front element,4: Insert at middle, 5: Delete from middle 6: to EXIT\n");

    int n;


    while(1){

    scanf("%d",&n);

    if(n==1)

    {

        printf("Enter the element you want to insert\n ");

        int t;

        scanf("%d",&t);

        enqueue(t);

        display();

    }

    else if(n==2)

    {

        dequeue();

        display();

    }

    else if(n==3)

    {

        qfront();

        display();


    }

    else if(n==4)

    {

       printf("Enter the element you want to insert\n ");

        int t;

        scanf("%d",&t);

        insertmiddle(t);

        display();

    }

    else if(n==5)

    {

        deletemiddle();

        display();

    }

    else if(n==6)

        break;

    printf("\n");

    }


return 0;

}



Post a Comment

0 Comments