public class LinkedQueue implements Queue { private class Node { private Object value; private Node next; private Node(Object value, Node next) { this.value = value; this.next = next; } } private Node front, rear; private int size, maxSize; public LinkedQueue() { front = rear = null; size = maxSize = 0; } public boolean isEmpty() { return front == null; } public boolean isFull() { return false; } public void enqueue(Object obj) { if (obj==null) throw new IllegalArgumentException(); Node newNode = new Node(obj, null); if (rear == null) { rear = newNode; front = rear; } else { rear.next = newNode; rear = newNode; } incrSize(); } public Object dequeue() { if (isEmpty()) throw new IllegalStateException("empty"); Object obj = front.value; front = front.next; if (front == null) rear = null; decrSize(); return obj; } public int size() { int n = 0; Node p=front; while (p!=null) { p = p.next; n++; } return n; } private void incrSize() { size++; if (size > maxSize) maxSize = size; } private void decrSize() { size--; } public int maxSize() { return maxSize; } public String toString() { String out = "front -> ["; if (! isEmpty()) { Node p = front; out = out + p.value; p = p.next; while (p != null) { out = out + ", " + p.value; p = p.next; } } out = out + "] <- rear"; return out; } public static void main(String[] args) { Queue q = new LinkedQueue(); for (int i=0; i< 10; i++) { q.enqueue("elem-" + i); System.out.println(q); } while (! q.isEmpty()) System.out.println(q.dequeue()); for (int i=0; i< 10; i++) { q.enqueue("elem-" + i); System.out.println(q); } while (! q.isEmpty()) System.out.println(q.dequeue()); } }