题解 | #数组元素反转#
数组元素反转
http://www.nowcoder.com/practice/8c9793ae96974a9ebb153d90ef31d357
#include <iostream>
using namespace std;
int main() {
int arr[6] = { 0 };
int len = sizeof(arr) / sizeof(int);
for (int i = 0; i < len; i++) {
cin >> arr[i];
}
cout << "[";
for (int i = 0; i < len; i++) {
if (i == len - 1) {
cout << arr[i] << "]" << endl;
break;
}
cout << arr[i] << ", ";
}
//方法一:使用一个辅助数组来进行更换
// int copy_arr[6] = { 0 };
// for(int i =len-1;i>=0;i--)
// {
// copy_arr[len-i-1]=arr[i];
// }
//方法二:使用双指针进行替换
int temp;
//指向首尾的双指针
int left = 0;
int right = 5;
while(left<right)
{
//对首尾的指针进行移动
temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
cout << "[";
for (int i = 0; i < len; i++) {
if (i == len - 1) {
cout << arr[i] << "]" << endl;
break;
}
cout << arr[i] << ", ";
}
return 0;
}