Created
January 27, 2021 18:20
-
-
Save Vishal1297/780a609f6f2edfa67af55ef1ad2fcf51 to your computer and use it in GitHub Desktop.
Queue Implementation Using Arrays.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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