实现数组头尾两端元素对调代码



深入理解计算机系统第二章p35页, 也是常见的面试题目,即不用第三个变量,实时交换二个数的值。利用对于数组元素个数为 偶数时,交换两端数组元素代码,当数组元素个数为奇数时,中间的元素将变为0,只需要将first<=last,改为first<last即可实现数组交换两端元素

#include<stdio.h>
void inplace_swap(int *x,int *y)
{
  *x = *x ^ *y;
  *y = *x ^ *y;
  *x = *x ^ *y;
}


void reverse_array(int a[],int cnt)
{
  int first,last;
  for(first = 0,last = cnt-1; first<=last;first++,last--)  //将红色的代码改为first<last,即可
  inplace_swap(&a[first],&a[last]);
}
int main()
{
       int b[ ] = {1,2,3,4}; //定义一个数组
       int c ;
  int i;
  c= sizeof(b)/sizeof(b[0]); //求数字元素的个数,注意不是sizeof(a),这样求的是数组的长度,而不是元素个数
         reverse_array(b,c);//函数调用
 for(i=0;i<c;i++)
 {
   printf("%d",b[i]);
 }
  printf(" ");


 return 0;
}

原文地址:https://www.cnblogs.com/riasky/p/3464994.html