public class p5b { static class LinkedListQueue<T> { private class Node<T> { private T data; private Node<T> next; Node(T data) { this.data = data; } } private Node<T> front, rear; void enqueue(T item) { Node<T> newNode = new Node<>(item); if (tail == null) front = rear = newNode; else { rear.next = newNode; rear = newNode; } } T dequeue() { if (front == null) System.out.println("Queue is empty"); T data = front.data; front = front.next; if (front == null) rear = null; return data; } } static class ArrayQueue<T> { private T[] array; private int front, rear, capacity; @SuppressWarnings("unchecked") ArrayQueue(int size) { capacity = size; array = (T[]) new Object[capacity]; } void enqueue(T item) { if ((rear + 1) % capacity == front) System.out.println("Queue is full"); array[rear] = item; rear = (rear + 1) % capacity; } T dequeue() { if (front == rear) System.out.println("Queue is empty"); T item = array[front]; front = (front + 1) % capacity; return item; } } public static void main(String[] args) { ArrayQueue<Integer> intQueue = new ArrayQueue<>(5); intQueue.enqueue(10); intQueue.enqueue(20); System.out.println(intQueue.dequeue()); System.out.println(intQueue.dequeue()); LinkedListQueue<String> stringQueue = new LinkedListQueue<>(); stringQueue.enqueue("Hello"); stringQueue.enqueue("World"); System.out.println(stringQueue.dequeue()); } }
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