【发布时间】:2021-12-17 00:48:30
【问题描述】:
我有一个 Queue 数据结构的手动实现,并试图将数字 1-10 排入最大大小为 10 的队列中。我的队列应该看起来像 1、2、3、4、5, 6,7,8,9,10,但由于某种原因,它看起来像 10,1,2,3,4,5,6,7,8,9。这是我的入队方法,我从后面添加每个元素:
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;
}
此外,当我尝试将数组中的所有数字出列,然后显示出列数字的乘积时,每次都应将前面的元素出列,但是,我出列数字的乘积不知何故为-10,而我的出队数组看起来像:10,1,2,3,4,5,6,7,8。这是我的出队方法:
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;
}
我还收到大量“无法出队,队列当前为空!”和“队列当前为空!”在我的控制台中输出。我哪里做错了?
【问题讨论】:
-
这似乎是错误的
else if(front == rear){ front = rear = -1;如果队列已满,前后也应该相同,但您似乎正在尝试将队列设置为“空”。
标签: java data-structures