public class ArrayQueue implements QueueInterface { private static final int CAPACITY = 1000; E[] queueArray; int front =0; int size=0; @Override public int size() { return size; } @Override public boolean isEmpty(){ return size==0; } @Override public E first() { if (isEmpty()) return null; return queueArray[front]; } @Override public void enqueue(E e) throws IllegalStateException { if (size==queueArray.length) throw new IllegalStateException("Queue full"); queueArray[(front+size)%queueArray.length] = e; size++; } @Override public E dequeue() { if (isEmpty()) return null; E e = queueArray[front]; queueArray[front] = null; front = (front+1)%queueArray.length; size--; return e; } public ArrayQueue() { this(CAPACITY); } @SuppressWarnings("unchecked") public ArrayQueue(int capacity) { queueArray = (E[])new Object[capacity]; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Siz:"); sb.append(size); sb.append(" Fnt:"); sb.append(front); sb.append(" ("); for (int i=front; i<(front+size); i++) { sb.append(queueArray[i]); if (i<(front+size-1)) sb.append(", "); } sb.append(")"); return sb.toString(); } public ArrayQueue merge(ArrayQueue qa, ArrayQueue qb) { ArrayQueue ret = new ArrayQueue<>(); while (qa.first()!=null || qb.first()!=null) { if (qb.first()==null) ret.enqueue(qa.dequeue()); else if (qa.first()==null) ret.enqueue(qb.dequeue()); else if (((Comparable)qa.first()).compareTo((Comparable)qb.first())<0) { ret.enqueue(qa.dequeue()); } else { ret.enqueue(qb.dequeue()); } } return ret; } public static void main(String[] args) { ArrayQueue qqa = new ArrayQueue<>(); ArrayQueue qqb = new ArrayQueue<>(); qqa.enqueue(1); qqa.enqueue(10); qqa.enqueue(11); qqa.enqueue(100); qqa.enqueue(101); qqa.enqueue(110); System.out.println(qqa); qqb.enqueue(1); qqb.enqueue(2); qqb.enqueue(10); qqb.enqueue(11); qqb.enqueue(12); qqb.enqueue(20); qqb.enqueue(21); qqb.enqueue(101); qqb.enqueue(102); qqb.enqueue(110); qqb.enqueue(111); System.out.println(qqb); ArrayQueue res = qqa.merge(qqa, qqb); System.out.println(res); } public static void mainB(String[] args) { ArrayQueue qqq = new ArrayQueue<>(); qqq.enqueue(2); System.out.println(qqq); qqq.enqueue(3); System.out.println(qqq); qqq.dequeue(); System.out.println(qqq); qqq.enqueue(7); System.out.println(qqq); qqq.dequeue(); System.out.println(qqq); System.out.println("First:"+qqq.first()); qqq.dequeue(); System.out.println(qqq); qqq.dequeue(); System.out.println("Empty: " + qqq.isEmpty()); qqq.enqueue(9); System.out.println(qqq); qqq.enqueue(7); System.out.println(qqq); System.out.println("Size: " + qqq.size()); qqq.enqueue(3); System.out.println(qqq); qqq.enqueue(5); System.out.println(qqq); qqq.dequeue(); System.out.println(qqq); } }