C 反向数组

新手上路,请多包涵

在 C++ 中,我需要:

  • 从用户输入中读取字符串并将其放入 char 数组 [完成]
  • 然后将该数组传递给函数[完成]
  • 该函数应该颠倒字符的顺序[问题!]
  • 然后,回到 main() ,它会显示带有新反转字符的原始数组。

我无法创建实际执行反转的函数,因为我有一些限制:

  • 我不能有任何本地数组变量。
  • 也没有指针

我的函数只传入原始数组,即:

 void reverse(char word[])

编辑: 到目前为止,这是我的代码库:

 void reverse(char word[]);

void main()
{
  char word[MAX_SIZE];

  cout << endl << "Enter a word : ";
  cin >> word;
  cout << "You entered the word " << word << endl;

  reverse(word);

  cout << "The word in reverse order is " << word << endl;
}

void reverse(char myword[])
{
  int i, temp;
  j--;

  for(i=0;i<(j/2);i++)
  {
    temp      = myword[i];
    myword[i] = myword[j];
    myword[j] = temp;

    j--;
  }
}

原文由 dazedandconfused 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 479
1 个回答

我可以使用算法 Depth first search 提供您问题的解决方案。

 #include <iostream>
#include <vector>
void showContentVector(std::vector<int>& input)
{
    for(int i=0; i<input.size(); ++i)
    {
        std::cout<<input[i]<<", ";
    }
    return;
}
void dfs(int current, int previous, std::vector<int>& input, std::vector<int>& visited)
{
    if(visited[current]==1)
    {
        return;
    }
    visited[current]=1;
    int item=input[current];
    for(int next=(current+1); next<input.size(); ++next)
    {
        if(next==previous)
        {
            continue;
        }
        dfs(next, current, input, visited);
    }
    if(current==input.size()-1)
    {
        input.clear();
    }
    input.push_back(item);
    return;
}
void solve()
{
    const int maximumSize=5;
    std::vector<int> values={1, 2, 3, 4, 5};
    std::vector<int> visited(maximumSize, 0);
    std::cout<<"Before, values <- ";
    showContentVector(values);
    dfs(0, -1, values, visited);
    std::cout<<std::endl<<"After, values <- ";
    showContentVector(values);
    std::cout<<std::endl;
    return;
}
int main()
{
    solve();
    return 0;
}

结果如下:

 Before, values <- 1, 2, 3, 4, 5,
After, values <- 5, 4, 3, 2, 1,

原文由 Vadim Chernetsov 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏