employer cover photo
employer logo

Domanda di colloquio di Opower

Implement a restricted size Queue.

Risposte di colloquio

Anonimo

13 gen 2012

private Object [] anArray; private int currentSize; private int front; private int back; static final int default_capacity=10; public interface QueueInterface{ pubilc boolean isFull(); public boolean isEmpty(); public void makeEmpty(); public Object dequeue(); public void enqueue(Object x); } public static void main (String [] args){ QueueAr q = new QueueAr(); try{ for (int i=0; i<10; i++){ q.enqueue(i); }catch (overflow e){ system.out.println("overflow"); } } public QueueAr (int capacity){ anArray = new Object [capacity]; makeEmpty(); } public boolean isEmpty(){ return currentSize==0; } public boolean isFull(){ return currentSize==anArray.length; } public void makeEmpty(){ currentSize=0; front =0; back = -1; } private int increment (int x){ if (++x==anArray.length) x=0; return x; } public Object dequeue(){ if(isEmpty()) return null; else curentSize --; Object frontItem=anArray [front]; anArray[front]=null; front = increment (front); return frontItem; } public void enqueue(Object x) throws Overflow{ if (isFull()) throw new Overflow(); else back = increment(back); anArray[back]=x; currentSize++; }

Anonimo

28 gen 2012

You throw an exception if array is full. Not happening. Rather create your own linked list in which you can ONLY enqueue and dequeue. Add size constraint. It would be very easy to do queue stuff this way. And thats the reason why Java queues implement List interface.

1