我有一个函数,它接受一个数组,以及一个随机的头和尾索引值。我试图从尾部值向后遍历整个数组,直到头部值,但似乎有些值被跳过了。
我的逻辑是:
currentRec = tail;
while (currentRec != head)
{
// get current record from array and do stuff (i.e. myArray[currentRec])
if (currentRec == 0)
{
currentRec = MAX_RECORDS - 1; // MAX_RECORDS is 200
}
else
{
currentRec--;
}
}
我错过了什么或做错了什么?
最佳答案
循环没有处理索引head
处的最后一个元素。如果要处理从tail
到head
的所有元素,则需要稍微更改逻辑:
currentRec = tail;
while (1)
{
// get current record from array and do stuff (i.e. myArray[currentRec])
if (currentRec == head) // if we've just processed the last (i.e. head) element
{
break; // exit loop
}
if (currentRec == 0) // otherwise bump currentRec and repeat...
{
currentRec = MAX_RECORDS - 1; // MAX_RECORDS is 200
}
else
{
currentRec--;
}
}
更新
如果您有额外的要求,当
head == tail
时,您需要处理数组中的所有元素,那么您需要添加更多的逻辑:currentRec = tail;
done = false;
while (1)
{
// get current record from array and do stuff (i.e. myArray[currentRec])
if (done) // if we've just processed the last (head) record
{
break; // exit loop
}
if (currentRec == 0)
{
currentRec = MAX_RECORDS - 1; // MAX_RECORDS is 200
}
else
{
currentRec--;
}
if (currentRec == head)
{
done = true; // set flag to indicate that the next iteration will be the last
}
}