Circular Queues

Implement basic operations on Circular Queue.

Source Code
#include<stdio.h>
void enqueue(int);
int dequeue();
int peek();
void display();
int n, front, rear, queue[30];
int main(){
  int ele, choice;
  printf("Enter size of Queue:\n");
  scanf("%d",&n);
  printf("::Circular Queue Operations::\n1. Enqueue\n2. Dequeue\n3. Peek\n4. Display\n5. Exit\n");
  front = rear = -1;
  do{
    printf("Select operation:\n");
    scanf("%d",&choice);
    switch(choice){
      case 1:
        if(rear==n-1 && front==0)
          printf("Queue is overflow.\n");
        else{
          if(front==-1)
            front = 0;
          printf("Enter new element:\n");
          scanf("%d",&ele);
          enqueue(ele);
        }
        break;
      case 2:
        if(front==-1 || front==rear){
          printf("Queue is underflow.\n");
          front = rear = -1;
        }else{
          ele = dequeue();
          printf("Deleted element is %d\n",ele);
        }
        break;
      case 3:
        if(front==-1 || front==rear){
          printf("Queue is empty.\n");
        }else{
          ele = peek();
          printf("Front element is %d\n",ele);
        }
        break;
      case 4:
        display();
        break;
      case 5:
        exit(0);
      default:
        printf("Invalid operation.\n");
    }
  }while(choice!=5);
  return 0;
}

void enqueue(int ele){
  rear = (rear+1)%n;
  queue[rear] = ele;
}

int dequeue(){
  int ele;
  ele = queue[front];
  front = (front+1)%n;
  return(ele);
}

int peek(){
  return(queue[front]);
}

void display(){
  int i;
  if(front==-1 || front==rear){
    printf("Queue is empty.\n");
  }else{
    printf("Queue elements are:\n");
    for(i=front;i!=rear;i=(i+1)%n)
      printf("%d ",queue[i]);
    printf("%d",queue[i]);
    printf("\n");
  }
}
Enter size of Queue:
4
::Circular Queue Operations::
1. Enqueue
2. Dequeue
3. Peek
4. Display
5. Exit
Select operation:
1
Enter new element:
5
Select operation:
1
Enter new element:
10
Select operation:
1
Enter new element:
15
Select operation:
1
Enter new element:
20
Select operation:
1
Queue is overflow.
Select operation:
4
Queue elements are:
5 10 15 20
Select operation:
3
Front element is 5
Select operation:
2
Deleted element is 5
Select operation:
4
Queue elements are:
10 15 20
Select operation:
1
Enter new element:
25
Select operation:
3
Front element is 10
Select operation:
4
Queue elements are:
10 15 20 25
Select operation:
5

No comments:

Post a Comment

Total Pageviews