Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

January 4, 2010

Java Implementation of Circular Queue

public class CircularQueue {

int[] cirQueue;

int front;

int rear;

// int size;
public CircularQueue(int size) {
cirQueue = new int[size];
front = rear = -1;
}

public static void main(String[] args) {
CircularQueue myQueue = new CircularQueue(5);
myQueue.insert(1);
myQueue.insert(2);
myQueue.insert(3);
myQueue.insert(4);
myQueue.insert(5);
myQueue.delete();
myQueue.insert(6);
myQueue.display();

}

public void delete() {
if (front == rear ) {
System.out.println("Can not delete from empty Queue");
return;
}else{
if(front==cirQueue.length)
front=0;
else
front++;
}
}

public void insert(int value) {
if ((rear + 1 == front) || (front == 0 && rear == cirQueue.length - 1)) {
System.out.println("Cant add ... Queue is full ");
return;
} else {
if (rear == cirQueue.length - 1) {
rear = 0;
}else{
rear++;
}
cirQueue[rear] = value;
}
if(front==-1)
front=0;
}

public void display(){
if(front > rear){
for(int i = front; i < cirQueue.length ; i++){
System.out.println(cirQueue[i]);
}
for(int i = 0 ; i < rear ; i++){
System.out.println(cirQueue[i]);
}
}else{
for(int i = front ; i < rear ; i++){
System.out.println(cirQueue[i]);
}
}
}
}

No comments: