import java.util.LinkedList;
public class GenericQueue<T> {
private LinkedList<T> queueList;
public GenericQueue() {
this.queueList = new LinkedList<>();
}
public void enqueue(T item) {
queueList.addLast(item);
}
public T dequeue() {
if (!queueList.isEmpty()) {
return queueList.removeFirst();
} else {
System.out.println("Queue Underflow");
return null;
}
}
public boolean isEmpty() {
return queueList.isEmpty();
}
public T peek() {
if (!queueList.isEmpty()) {
return queueList.getFirst();
} else {
return null;
}
}
public static void main(String[] args) {
GenericQueue<Integer> intQueue = new GenericQueue<>();
intQueue.enqueue(1);
intQueue.enqueue(2);
intQueue.enqueue(3);
intQueue.enqueue(4);
intQueue.enqueue(5);
System.out.println("Front element: " + intQueue.peek()); // 1
while (!intQueue.isEmpty()) {
System.out.println("Dequeued element: " + intQueue.dequeue());
}
System.out.println("Queue is empty: " + intQueue.isEmpty()); // true
GenericQueue<String> stringQueue = new GenericQueue<>();
stringQueue.enqueue("one");
stringQueue.enqueue("two");
stringQueue.enqueue("three");
System.out.println("Front element: " + stringQueue.peek()); // one
while (!stringQueue.isEmpty()) {
System.out.println("Dequeued element: " + stringQueue.dequeue());
}
System.out.println("Queue is empty: " + stringQueue.isEmpty()); // true
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter