Uploaded by Dhyan Sai

BoundedQueue

advertisement
Name: Venkata Bhavana Vijay Srinivas Panchangam
UTD ID: 2021625801
Net Id: VXP210036
import java.util.*; public class BoundedQueue<T>{
int rear; // rear to point to the end of the queue and to add new elements
int front; // front to point to first element of queue and to remove elements
int capacity; // Capacity of the Bounded queue
private Object[] queue; // To store Queue elements
int size;
public BoundedQueue(int size) {
rear = 0;
front=0;
this.size=size;
capacity = size;
queue= new Object[size];
Scanner sc=new Scanner(System.in); //adding elements to the queue.
System.out.println("Enter the number of elements in queue");
int m;
m=sc.nextInt();
for(rear=0;rear<m;rear++)
{
queue[rear]=sc.nextInt();
}
}
public boolean offer(T x) { //Adding element to the end of the queue
if(capacity==size()) //if queue is full, return false
return false;
if(front!=rear) { // If queue is not empty
rear = (rear+1)%capacity;
}
else {
// If queue is empty
front=0;
rear=0;
}
// Add the new element at rear position
queue[rear] = x;
return true;
}
public T poll() { // Removes the element at first position of the queue
if(front==0&&rear==0)
return null; // queue is empty
//remove first element
T t = (T)queue[front];
if(front==rear) {
front=-1;
rear = -1;
}
else {
front = (front+1)%capacity; //updating front
}
return t;
}
// Returns the front element in the queue
public T peek() {
if(front==1&&rear==-1)
return null;
return (T)queue[front];
}
// returns the size of the queue
public int size() {
if(front==-1 && rear==-1)
return 0;
else if(front<=rear)
return rear-front;
else
return capacity - front+rear; // front > rear }
//main function
public static void main(String args[])
{
int size = 10;
BoundedQueue<Integer> que = new BoundedQueue<>(size);
Scanner sc = new Scanner(System.in);
System.out.println(" 1 - Offer; 2- Poll; 3- Peek; 4-Size");
whileloop: while (sc.hasNext()) {
int opn = sc.nextInt();
switch (opn) { //using switch case inorder to allow the user to access all the possible methods
case 1: // Offer
System.out.print("Enter element to add: ");
if(que.offer(sc.nextInt()))
System.out.println("true");
else
System.out.println("false");
break;
case 2: // Poll System.out.println("Element removed: " + que.poll());
break;
case 3: // Peek
System.out.println("Peek: " + que.peek());
break;
case 4: // Size method
System.out.println("Size: " + que.size());
break;
default: // Exit loop
break whileloop;
}
} }
}
Download