Data structure: C language realizes the reverse order of the array, and the space complexity is O(1)

Ideas

  1. Calculate the length of the array
  2. The first and the penultimate position interchange; the i-th position interchanges with the length-1-i-th position
  3. Loop half of the array

The following is the code, which can be run directly:

#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;
}

Guess you like

Origin blog.csdn.net/qq_24130591/article/details/106592370