数据结构:C语言实现数组逆序,空间复杂度为O(1)

思路

  1. 计算数组长度
  2. 第一个与倒数第一个互换位置;第i个位置与第length-1-i个位置互换
  3. 循环数组一半位置即可

以下为代码,可直接运行:

#include <stdio.h>

int main()
{
	int l[10] = {10,9,8,7,6,5,4,3,2,1};
	int temp,position;
	int length =sizeof(l)/sizeof(int); 
	printf("This length of array = %d\n",length);
	for(int i = 0;i<length;i++)
	{
		printf("%d",l[i]);
	}
    printf("\n-----This is a separation line--------\n");
	for(int i=0;i<length/2;i++)
	{
		temp = l[i];
		position = length-1-i;
		l[i] = l[position];
		l[position] = temp;
	}
    for(int i = 0;i<length;i++)
	{
		printf("%d",l[i]);
	}
 
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_24130591/article/details/106592370
今日推荐