【问题描述】设顺序表L中数据元素均为整型,设计一个高效算法,将L中所有元素逆置,要求算法空间复杂度为O(1)
【输入形式】
第一行包括一个整数n,第二行为n个整数,以空格分开
【输出形式】
逆序输出n个整数,以空格分开;若n=0, 则输出"Empty"
【样例1输入】
10
12 31 11 26 12 2 19 33 43 33
【样例1输出】
33 43 33 19 2 12 26 11 31 12
#include<stdio.h>
#include<malloc.h>
#include<iostream>
using namespace std;
#define LIST_INIT_SIZE 100
typedef struct
{
int * elem;
int length;
int listsize;
}sqlist;
void Reverse(sqlist& L)
{
//int *p=L.elem;
//int *q=L.elem+L.length-1;
//for(;p<q;p++,q--)
//{
// int t=*p;
// *p=*q;
// *q=t;
//}
int i=0;
for(;i<L.length/2;i++)
{
int t=L.elem[i];
L.elem[i] = L.elem[L.length-1-i];
L.elem[L.length-1-i]=t;
}
}
int InitList(sqlist &L)
{
L.elem = (int *)malloc(LIST_INIT_SIZE*sizeof(int));
if(!L.elem) exit(-1);
L.listsize = LIST_INIT_SIZE;
return 1;
}
int main()
{
sqlist L;
int i;
scanf("%d",&L.length);
if(L.length!=0)
{ InitList(L);
for(i=0;i<L.length;i++)
scanf("%d",&L.elem[i]);
Reverse(L);
for(i=0;i<L.length;i++)
printf("%d ",L.elem[i]);
}
else
printf("Empty");
return 0;
}