后值在循环数组队列中无法正常工作
我有这样的代码用于添加:
public void add(AnyType item){
if(isEmpty()){
q[f]=item;
}
else{
if(size==q.length){
AnyType[] copyQ = (AnyType[]) new Object[q.length*2];
System.arraycopy(q, f, copyQ, 0, q.length-f);
System.arraycopy(q, 0, copyQ, q.length-f, r);
f = 0;
q = copyQ;
}
}
q[r]=item;
r = (r+1)%(q.length);
size++;
}
但是当我想要获取 r 的值时,它给了我比实际值多一个的值。另外,当我将值从一个数组复制到另一个数组时,有一个值正在跳过一个值。我知道一切都与 r = (r+1)%(q.length); 的值有关,我已经研究了几个小时但无法弄清楚。 将值分配给 q[r] 后,即使它只是第一个值,并且我尝试获取 r 应该在哪里的值,它也会给我 1,因为它是通过公式增加的,但我无法弄清楚如何以不同的方式编写它而不弄乱循环队列公式。 任何帮助将不胜感激。谢谢!
I have this code for adding:
public void add(AnyType item){
if(isEmpty()){
q[f]=item;
}
else{
if(size==q.length){
AnyType[] copyQ = (AnyType[]) new Object[q.length*2];
System.arraycopy(q, f, copyQ, 0, q.length-f);
System.arraycopy(q, 0, copyQ, q.length-f, r);
f = 0;
q = copyQ;
}
}
q[r]=item;
r = (r+1)%(q.length);
size++;
}
But then when I want to get the value of r
it gives me one more value than it actually is. Also, when I copy the values from one Array to the other there is a value that it is skipping one value. I know everything has to do with the value of r = (r+1)%(q.length);
and I've been working on it for hours and can't figure it out.
After assigning the value to q[r], even if it is only the first value, and I try to get the value of where r should be it gives me 1 because it is increased by the formula, but I can't figure out how to write it in a different way without messing up the circular queue formula.
Any help would be greatly appreciated. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
单元测试是你的朋友! :-)
将您想要的行为表达为测试,逐渐增加
add()
方法的复杂性,直到一切正常。我为你的循环缓冲区做了它,工作的add()
看起来像这样:注意差异:
r
是一个偏移量 - 你不能将它用作长度 第二个arraycopy()
r
更改了计算顺序,在 之前递增r
em> 存储项目
Unit tests are your friend! :-)
Express your desired behaviour as tests, gradually building up complexity in your
add()
method until it all works. I did it for your circular buffer and the workingadd()
looked like this:Note the differences:
r
is an offset - you can't use it as a length in the secondarraycopy()
r
needs to be updated when you resize your internal arrayr
before storingitem
是因为最后三行应该在 else 块内吗?尝试如下代码:
当三行位于 else 块之外时,您将添加新元素两次,以防数据结构为空。
Is it because the the last three lines should in within the else block? Try a code like:
When the three lines are outside the else block, you were adding the new element twice in case when the data structure is empty.