C编程乐趣

本文介绍了一种使用位运算实现数组中元素头尾互换的方法,通过自定义函数`inplace_swap`和`reverse_array`,演示了如何在不使用额外变量的情况下完成元素交换操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 看《深入理解计算机系统》时候看到的方法,觉得很cool
    不需要第三个位置来临时存储另一个值来实现两个数值的交换
    void inplace_swap(int *a, int *b)
    {
    	*a = *a ^ *b;
    	*b = *a ^ *b;
    	*a = *a ^ *b;
    }
  2. 利用上面的函数 ,实现将一个数组中的元素头尾两端依次对调
    void reverse_array(int a[], int cnt)
    {
    	int first, last;
    	for(first=0, last=cnt-1; first<last; first++,last--)
    	{
    		inplace_swap(&a[first], &a[last]);
    	}
    }
    实现程序:
    #include <stdio.h>
    #include <stdlib.h>
    void inplace_swap(int *a, int *b);
    void reverse_array(int a[], int cnt);
    void main(void)
    {
    	int a[100];
    	int i, len = 0;
    	printf("输入数组元素:\n");
    	for (i=0; i<100 && scanf("%d", &a[i])!=NULL; i++)
    	{
    		len++;
    	}
    	reverse_array(a, len);
    	printf("输出对调后的数组元素\n");
    	for(i=0; i<len; i++)
    	{
    		printf("%d ", a[i]);
    	}
    	system("pause");
    }
    void inplace_swap(int *a, int *b)
    {
    	*a = *a ^ *b;
    	*b = *a ^ *b;
    	*a = *a ^ *b;
    }
    //实现将一个数组中的元素头尾两端依次互调
    void reverse_array(int a[], int cnt)
    {
    	int first, last;
    	for(first=0, last=cnt-1; first<last; first++,last--)
    	{
    		inplace_swap(&a[first], &a[last]);
    	}
    }



      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值