Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement the peek and peekAt methods of the below ArrayQueue class so that peek

ID: 3862562 • Letter: I

Question

Implement the peek and peekAt methods of the below ArrayQueue class so that peek returns the item at the front of the queue and peekAt returns the i-th item from the front of the queue, e.g., for i = 0, the method peekAt should return the same item as peek. public class ArrayQueue {private Item[] q; private int front = 0, end = 0; public ArrayQueue() {q = (Item []) new Object[8];} public void enqueue(Item item) {q[end] = item; end = (end + 1) % q.length;} public Item dequeue() {Item item = q[front]; front = (front + 1) % q.length; return item;} public Item peek() {//TODO} public Item peekAt(int i) {//TODO}}

Explanation / Answer

public class ArrayQueue<Item>
{

private Item[] q;
private int front=0,end=0;
public ArrayQueue()
{
q=(Item[])new Object[8];
}
public void enqueue(Item item)
{
q[end]=item;
end=(end+1)%q.length;
}
public Item dequeue()
{
Item item=q[front];
fron(front+1)% q.length;
return item;
}
public Item peek()
{
if(front==0)
return 0;
else
{ return q[front];
}

}
public Item peekAt(int i)
{

int j;
for(j=front;j<=end;j++)
{
if(j==i)
return q[j];
}

}