我刚刚和我的 friend 一起尝试了一些数据结构问题。我从一位 friend 那里遇到了这个问题,他也无法解决。
Question: Reverse an array without changing position of zeroes. example : if array has has 0 5 7 8 0 9 then the result should be 0 9 8 7 0 5.
我尝试过,但它在所有情况下都不能正确执行,如果代码看起来很难看,我很抱歉我现在是新手。
#include<iostream>
using namespace std;
int main()
{
int arr[100], tot, i, j, temp;
cout<<"Enter the Size for Array: ";
cin>>tot;
cout<<"Enter "<<tot<<" Array Elements: ";
for(i=0; i<tot; i++)
cin>>arr[i];
cout<<"\nThe Original Array is:\n";
for(i=0; i<tot; i++)
cout<<arr[i]<<" ";
j = tot-1;
for(i=0; i<j; i++, j--)
{
if(arr[i] == 0) {
i++;
continue;
}else if(arr[j] == 0) {
j--;
continue;
}
else {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
cout<<"\n\nThe Reverse of Given Array is:\n";
for(i=0; i<tot; i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}
我已经尝试了上面的代码,但它没有给出正确的结果。
最佳答案
这里的问题是,您在循环的每次迭代中都修改了循环变量 i
和 j
;仅当元素被交换时才需要更新:
for(i=0; i<j;)
{
if(arr[i] == 0) {
i++;
}else if(arr[j] == 0) {
j--;
}
else {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
++i;
--j;
}
}
关于c++ - 反转数组而不改变零的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74873752/