数据结构之数组翻转的实现方法
以下为实现数组翻转的方法:
1.用c语言实现的版本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
#include<stdio.h>
#define M 20
void fun( int *x, int n)
{
int *i, *j, *p, m=n/2;
i = x;
j = x+n-1;
p = x+m;
for ( ; i<p; ++i,--j)
{
int t = *i;
*i = *j;
*j = t;
}
}
void main()
{
int i,a[M],n;
printf ( "Enter n(n<20):\n" );
scanf ( "%d" ,&n);
printf ( "The original array:\n" );
for (i=0; i<n; ++i)
{
scanf ( "%d" , a+i);
}
fun(a,i);
printf ( "\nThe array inverted:\n" );
for (i=0; i<n; ++i)
{
printf ( "%d " , *(a+i));
}
printf ( "\n" );
}
|
2. 用c++实现的版本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
#include<iostream>
#define M 20
void fun( int *x, int n)
{
int *i, *j, *p, m=n/2;
i = x;
j = x+n-1;
p = x+m;
for ( ; i<p; ++i,--j)
{
std::swap(*i,*j);
}
}
void main()
{
<span style= "white-space:pre" > </span> int i,a[M],n;
<span style= "white-space:pre" > </span>std::cout<< "Enter n(n<20):" <<std::endl;
std::cin>>n;
std::cout<< "The original array:" <<std::endl;
<span style= "white-space:pre" > </span> for (i=0; i<n; ++i)
{
std::cin>>*(a+i);
}
<span style= "white-space:pre" > </span> fun(a,i);
std::cout<<std::endl<< "The array inverted:" <<std::endl;
<span style= "white-space:pre" > </span> for (i=0; i<n; ++i)
{
std::cout<<*(a+i)<< " " ;
}
std::cout<<std::endl;
}
|
效果图如下:
3. 用PHP实现的版本
1
2
3
4
5
6
7
8
9
|
<?php
$arrOrigin = array (1,2,3,4,5,6,7,8,9,10);
$arrReverse = array_reverse ( $arrOrigin );
echo '原始数组:' ;
print_r( $arrOrigin );
echo '<br/>' ;
echo '翻转后的数组:' ;
print_r( $arrReverse );
?>
|
结果如下所示:
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://blog.csdn.net/chinawangfei/article/details/52911026