C++ 下面给出用数组的方法将数组a中的n个整数按相反顺序存放,请用指针的方法重写^_^

#include<iostream.h>
void inv(int x[],int n)
{
int temp,i,j,m=(n-1)/2;
for(i=0;i<=m;i++)
{
j=n-1-i;
temp=x[i];x[i]=x[j];x[j]=temp;
}
}
void main()
{int i,a[10]={3,7,9,11,0,6,7,5,4,2};
cout"The original array:\n";
for(i=0;i<10;i++)
cout<<a[i]<<” “;
cout<<endl;
inv(a,10);
cout<<"The array has benn inverted:\n";
for(i=0;i<10;i++)
cout<<a[i]<<” “;
cout<<endl;
}

用指针遍历数组,有两种方法:

    按偏移位置引用数据(类似数组元素引用)

    移动指针,取当前位置数据

参考代码:

//按偏移位置引用数据
void inv(int x[],int n)
{
    int i;
    for( i=0;i<n/2;i++ )
    {
        int temp=*(x+i); //相当于temp=x[i]
        *(x+i)=*(x+n-i-1);//相当于x[i]=x[n-i-1] ;
        *(x+n-i-1)=temp;
    }
}
//移动指针,通过指针访问数组
void inv(int x[],int n)
{
    int *h,*t;
    h=x ; //数组头
    t=x+n-1; //数组尾
    while( t>h ) //尾大于头时,进行头尾数据交换
    {
        int temp=*h;
        *h=*t;
        *t=temp;
        h++;t--; //头指针后移,尾指针前移
    }
}

温馨提示:内容为网友见解,仅供参考
第1个回答  2009-05-03
void inv(int *x,int n)
{
int t,mid = n/2;
for(int i = 0;i<mid;++i)
{
t = *(x + n - 1 - i);
*(x + n - 1 - i) = *(x + i);
x(x + i) = t;
}
}
写完后发现与 梦想窗外 的算法雷同,不是抄袭,也还是写上吧~
第2个回答  2009-05-03
#include<iostream.h>

typedef struct _node
{
int data;
struct _node *next; //单链表
}_tag_NODE;

bool converts(_tag_NODE *head)
{
_tag_NODE *move,*pTemp,*tail;
_tag_NODE *a[1000];//空间换时间
int dex =0;
pTemp =head;
while(NULL != pTemp->next)
{
a[dex] = pTemp;
pTemp = pTemp->next;
dex++;
}
a[dex] = pTemp;

for(int i=head->data;i>=1;i--)
{
a[i]->next = a[i-1];
}
head->next = a[head->data];
a[1]->next =NULL;
return true;
}

bool insertDataNoSeq(_tag_NODE *head,int dataIn)//直接插入数据到末尾
{
_tag_NODE *pTemp,*pNew;
pNew =NULL;

pTemp = head;

if(pTemp == NULL)
{
pTemp = new _tag_NODE;
pTemp->next =NULL;
head = pTemp;
head->data = 0;
}
while(NULL!=pTemp->next)
{
pTemp = pTemp->next;
}
pNew = new _tag_NODE;
if(NULL!=pNew ) //分配失败
{
pTemp->next = pNew;
pNew->data = dataIn;
pNew->next =NULL;
}
else
{
return false;
}
head->data ++;//记录链表中数据的个数
return true;
}

void showMyList(_tag_NODE *head)
{
_tag_NODE *pTemp;
pTemp = head;

if(NULL==pTemp )
{
return;
}
cout<<endl;
while(NULL!=pTemp->next)
{
pTemp = pTemp->next;
cout<<pTemp->data <<" ";

}
}

void main()
{
int i,a[10]={3,7,9,11,0,6,7,5,4,2};
_tag_NODE *head;
head = NULL;
head = new _tag_NODE;
head->next =NULL;
head->data =0;

for(i=0;i<10;i++)
{
insertDataNoSeq(head,a[i]); //暂不考虑返回FALSE的情况
}
showMyList(head);
converts(head);
showMyList(head);
}

结果:

3 7 9 11 0 6 7 5 4 2
2 4 5 7 6 0 11 9 7 3 Press any key to continue
第3个回答  推荐于2016-06-19
#include <iostream.h>

void inv(int *x,int n)
{
for (int i = 0; i < n / 2; ++i)
{
int temp = *(x + i);
*(x + i) = *(x + n - 1 - i);
*(x + n - 1 - i) = temp;
}
}
void main()
{
int i,a[10]={3, 7, 9, 11, 0, 6, 7, 5, 4, 2};
cout << "The original array:\n";
for(i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
inv(a, 10);
cout<<"The array has benn inverted:\n";
for(i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
}本回答被提问者采纳
相似回答