【发布时间】:2009-10-23 21:47:31
【问题描述】:
我为我的堆栈对象类开发了一种称为“旋转”的方法。我所做的是,如果堆栈包含元素:{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;
}
}
}
}
【问题讨论】:
-
你打算怎么用这个?您是一次访问一个结果,还是想要传递整个数组?
-
这是一个控制台应用程序。我只是逐个打印每个元素。
-
使用链表会让事情变得容易很多。
-
是否考虑过使用 STL 算法 std::rotate ?