Implement data structure overflow queue. Overflow queue is a normal queue with one extra property. It never throw
Stack overflow exception. So whenever queue becomes full, it replaces the oldest element present in the queue and
front pointer simply shifted one step ahead.
Constraint:- it should have public void enQueue(int n) and public int deQueue() methods of time complexity O(1)
The implementation should be optimum and clean.
Please leave comments.
public class OverflowQueue { private int[] queue; private int front = -1, rear = -1; public OverflowQueue(int size) { queue = new int[size]; } public void enQueue(int n){ rear = getNextIndex(rear); queue[rear] = n; if (rear == front || front == -1){ front = getNextIndex(front); } } private int getNextIndex(int index){ if (index == queue.length - 1 ){ index = 0; } else { index ++ ; } return index; } public int deQueue(){ if (front == -1 ){ throw new NullPointerException("deQueue operation is called on empty queue."); } int elem = queue[front]; if (front == rear ){ front = -1; rear = -1; } else { front = getNextIndex(front); } return elem; } public static void main(String[] args) { OverflowQueue q = new OverflowQueue(5); q.enQueue(1);q.enQueue(2);q.enQueue(3); q.enQueue(4);q.enQueue(5);q.enQueue(6); System.out.println(q.deQueue()); System.out.println(q.deQueue()); System.out.println(q.deQueue()); System.out.println(q.deQueue()); System.out.println(q.deQueue()); } }
Please leave comments.
Nice
ReplyDelete