public class BoundedIntQueue { int[] queue; int startIndex; int endIndex; int size; public BoundedIntQueue(int queueSize) { queue = new int[queueSize]; startIndex = 0; endIndex = 0; size = 0; } public int dequeue() throws Exception{ int result = 0; // check if queue is empty, throw exception if empty if(size<=0){ throw new Exception("Queue Empty"); }else{ // dequeue element in queue, if queue is not empty result = queue[startIndex]; adjustStartIndexAfterDequeue(); size--; } return result; } private void adjustStartIndexAfterDequeue(){ startIndex++; if(startIndex >= queue.length) startIndex = 0; if(startIndex < 0) startIndex = queue.length -1; } public void enqueue(int x) throws Exception{ // check if queue is full, throw exception if full if(size >= queue.length){ throw new Exception("Queue Full"); }else{ // insert element in queue, if queue is not full queue[endIndex] = x; adjustEndIndexAfterEnqueue(); size++; } } private void adjustEndIndexAfterEnqueue(){ endIndex++; if(endIndex < 0) endIndex = queue.length -1; if(endIndex >= queue.length) endIndex = 0; } }
Saturday, July 24, 2010
Simple Queue Implementatino in Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment