我为我的堆栈对象类开发了一种称为“旋转”的方法。我所做的是,如果堆栈包含元素:{0,2,3,4,5,6,7},我需要向前和向后旋转元素。
如果我需要向前旋转 2 个元素,那么数组中会有 {3,4,5,6,7,0,2}。如果我需要向后旋转,或 -3 个元素,那么,查看原始数组,它会是 {5,6,7,0,2,3,4}
所以我开发的方法工作正常。 IMO 的效率非常低下。我想知道是否可以使用 mod 运算符环绕数组?或者如果他们是我还没有意识到的无用代码,等等。
我想我的问题是,如何简化此方法?例如使用更少的代码。 :-)
void stack::rotate(int r)
{
int i = 0;
while ( r > 0 ) // rotate postively.
{
front.n = items[top+1].n;
for ( int j = 0; j < bottom; j++ )
{
items[j] = items[j+1];
}
items[count-1].n = front.n;
r--;
}
while ( r < 0 ) // rotate negatively.
{
if ( i == top+1 )
{
front.n = items[top+1].n;
items[top+1].n = items[count-1].n; // switch last with first
}
back.n = items[++i].n; // second element is the new back
items[i].n = front.n;
if ( i == bottom )
{
items[count-1].n = front.n; // last is first
i = 0;
r++;
continue;
}
else
{
front.n = items[++i].n;
items[i].n = back.n;
if ( i == bottom )
{
i = 0;
r++;
continue;
}
}
}
}
最佳答案
您可以更改“开始”的定义,而不是移动堆栈中的所有项目。有一个代表堆栈中第一项的索引,开始时为 0,只要您想旋转堆栈,就可以使用模块化算法对其进行添加和减去。
请注意,如果您采用这种方法,您不应该让您的类的用户访问底层数组(无论如何您真的应该......)。
关于c++ - 移动数组中的元素 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1616086/