在堆栈中移动元素

Moving Elements In A Stack

本文关键字:元素 移动 堆栈      更新时间:2023-10-16

我有一个使用数组实现的堆栈,它将6个字符作为用户的输入(小案例和大写字母)。然后将上箱字母转移到另一个堆栈(将其从原始堆栈中删除)

我有以下代码,它将元素沿堆栈移动到顶部,然后将其推到顶部并将其推到新数组。

for (int i = P->top(); i >= 0; i--)
{
  if (P->data[i] >= 65 && P->data[i] <= 90)
  {
    for (int j = i; j < P->top(); i++)
    {
      char swap = P->data[i + 1];
      P->data[i + 1] = P->data[i];
      P->data[i] = swap;
      stackT.push(P->pop());
      i = P->top();
    }
  }
}

我应该还有另一个带有大写字母的阵列,而原始的则带有小写字母。

它得到了奇怪的结果,有时它会完全摧毁原始数组,有时它只会传递一个高层元素并弄乱了其他元素。

我只是没有想法。

是的,问题仅限于堆栈的使用,而不是这不是作业。

预先感谢!

不要在内部移动事物
(我希望本练习的目的是您仅使用堆栈操作,并且只能在"顶部"上修改堆栈 - 其他任何东西都不是堆栈。)

而是使用第三个临时的堆栈。

stack original = .. whatever ...;
stack uppercase;
stack other;
// Classify the contents
while (!original.empty())
{
    char c = original.top();
    original.pop();
    if (std::isupper(c))
    {
        uppercase.push(c);
    }
    else
    {
        other.push(c);
    }
}
// Restore the non-uppercase stack.
while (!other.empty())
{
    original.push(other.top());
    other.pop();
}