0

I have a manual implementation of the Queue data structure, and am trying to enqueue the numbers 1-10 inside a queue of a maximum size of 10. My queue should then look like 1,2,3,4,5,6,7,8,9,10, but for some reason, it looks like 10,1,2,3,4,5,6,7,8,9. Here is my enqueue method, where I am adding each element from the rear:

public int enqueue(int n) { //where n is the item we want to add if(isFull()){ //checks to see if rear+1 % data.length == front System.out.println("Cannot add item, queue is currently full."); return n; } else if(isEmpty()){ //checks to see if the front = rear = -1 front = rear = 0; rear+=1; } else{ //allows for cyclic array rear = (rear + 1) % data.length; } data[rear] = n; size ++; return n; } 

Additionally, when I try to dequeue all the numbers from the array, and then display the product of the dequeued numbers, the front element should be dequeued every time, however, the product of my dequeued numbers is somehow -10 and my dequeued array looks like: 10,1,2,3,4,5,6,7,8. Here is my dequeue method:

public int dequeue() { //remove the object from the front of queue if(front == -1 && rear == -1){ //need for the and condition? System.out.println("Cannot dequeue, queue is currently empty!"); return -1; } else if(front == rear){ front = rear = -1; } else{ front = (front + 1) % data.length; } size --; return 0; } 

I also get a ton of "Cannot dequeue, queue is currently empty!" and "Queue is currently empty!" outputs in my console. Where did I go wrong?

1
  • This seems wrong else if(front == rear){ front = rear = -1; front and rear should also be the same if the queue is full, but you seem to being trying to set the queue to "empty" here. Commented Dec 17, 2021 at 1:43

1 Answer 1

0

In enqueue, you just need to store the value, increment rear and size. In dequeue, you just need to increment front and decrement size.

 private final int[] data = new int[10]; private int size, front, rear; public int enqueue(int n) { if (size == data.length) { throw new RuntimeException("Queue is full."); } data[rear] = n; rear = (rear + 1) % data.length; size++; return n; } public int dequeue() { if (size == 0) { throw new RuntimeException("Queue is empty."); } int e = data[front]; front = (front + 1) % data.length; size--; return e; } 
Sign up to request clarification or add additional context in comments.

Comments