Skip to content

Instantly share code, notes, and snippets.

@Vishal1297
Created January 27, 2021 18:20
Show Gist options
  • Save Vishal1297/780a609f6f2edfa67af55ef1ad2fcf51 to your computer and use it in GitHub Desktop.
Save Vishal1297/780a609f6f2edfa67af55ef1ad2fcf51 to your computer and use it in GitHub Desktop.
Queue Implementation Using Arrays.
public class Main {
public static void main(String[] args) {
QueueUsingArray queue = new QueueUsingArray();
System.out.println(queue.isFull()?"Full":"Not Full");
System.out.println(queue.isEmpty()?"Empty":"Not Empty");
queue.enQueue(11);
queue.enQueue(101);
queue.enQueue(1111);
System.out.println("Peek at 2 " + queue.peek(2));
queue.enQueue(1221);
System.out.println("Elements");
queue.printQueue();
System.out.println(queue.isEmpty()?"Empty":"Not Empty");
queue.deQueue();
queue.deQueue();
queue.deQueue();
System.out.println("Elements");
queue.printQueue();
System.out.println("Peek at 2 "+ queue.peek(1));
System.out.println(queue.isFull()?"Full":"Not Full");
queue.deQueue();
queue.deQueue();
System.out.println(queue.isFull()?"Full":"Not Full");
}
}
// Queue Implementation Using Arrays
class QueueUsingArray {
private int size = 10;
private Object[] queue = new Object[size];
private int frontIndex = 0;
private int rearIndex = 0;
public void enQueue(Object element) {
if (isFull()) {
System.out.println("Queue is full.");
} else {
queue[rearIndex] = element;
rearIndex++;
}
}
public Object deQueue() {
if (isEmpty()) {
System.out.println("Queue is empty.");
return -1;
} else {
Object obj = queue[frontIndex];
queue[frontIndex] = 0;
frontIndex++;
return obj;
}
}
public Object peek(int position) {
if (queue[position] == null) {
System.out.print("No Element At " + position + " ");
return -1;
} else {
if (position == frontIndex)
return queue[position];
else {
return queue[frontIndex + position - 1];
}
}
}
public Object getFirst() {
return queue[frontIndex];
}
public Object getLast() {
return queue[rearIndex];
}
public boolean isEmpty() {
return rearIndex <= 0;
}
public boolean isFull() {
return rearIndex + 1 == size;
}
public void printQueue() {
for (int index = frontIndex; index < rearIndex; index++) {
System.out.print(queue[index] + " ");
}
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment