Implement a fix-sized queue using array.
import java.util.*;
public class Queue<T> {
private int front;
private int rear;
private int size;
private final T[] queue;
public Queue(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException("Size cannot be less than or equal to zero.");
}
size = 0;
front = 0;
rear = -1;
queue = (T[])new Object[capacity];
}
public int size() {
return size;
}
public void enQueue(T item) {
if (size == queue.length) {
throw new IllegalStateException("Queue is full.");
}
rear = (rear + 1) % queue.length;
queue[rear] = item;
size++;
}
public T deQueue() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty.");
}
T value = queue[front];
front = (front + 1) % queue.length;
size--;
return value;
}
public boolean isEmpty() {
return size == 0;
}
public T peek() {
if (isEmpty()) {
throw new IllegalStateException("Queue is Empty.");
}
return queue[front];
}
@Override
public String toString() {
int s = size;
int head = front;
String str = "[";
while (s > 1) {
str += queue[head];
str += ", ";
s--;
head = (head + 1) % queue.length;
}
if (s == 1) {
str += queue[head];
}
str += "]";
return str;
}
public static void main(String[] args) {
Queue<Integer> newQueue = new Queue<>(5);
newQueue.enQueue(10);
newQueue.enQueue(20);
newQueue.enQueue(30);
newQueue.enQueue(40);
newQueue.enQueue(50);
System.out.println(newQueue.toString());
System.out.println(newQueue.deQueue().toString());
System.out.println(newQueue.deQueue().toString());
System.out.println(newQueue.toString());
newQueue.enQueue(60);
newQueue.enQueue(70);
System.out.println("Size should be 5, the result is " + newQueue.size());
System.out.println("Should be false, the result is " + newQueue.isEmpty());
System.out.println(newQueue.toString());
System.out.println(newQueue.deQueue().toString());
System.out.println(newQueue.deQueue().toString());
System.out.println(newQueue.deQueue().toString());
System.out.println(newQueue.deQueue().toString());
System.out.println(newQueue.deQueue().toString());
System.out.println(newQueue.toString());
System.out.println("Size should be 0, the result is " + newQueue.size());
System.out.println("Should be true, the result is " + newQueue.isEmpty());
}
}
No comments:
Post a Comment