逆置线性表,使空间复杂度为 O(1)
#include <iostream>
using namespace std;
typedef int ElemType;
#define Maxsize 100
#define OK 1
#define ERROR 0
typedef struct SqList
{
ElemType data[Maxsize];
int length;
}SqList;
void Init_SqList(SqList& L)
{
L.length = 0;
}
//逆置线性表,使空间复杂度为 O(1)
void inverse(SqList& L)
{
int temp = 0;
for (int i = 0; i <= (0 + L.length - 1) / 2; i++)
{
temp = L.data[i];
L.data[i] = L.data[L.length - 1 - i];
L.data[L.length - 1 - i] = temp;
}
}
void inverse1(SqList& L)
{
for (int i = 0, j = L.length - 1; i < j; i++, j--)
{
int t = L.data[i];
L.data[i] = L.data[j];
L.data[j] = t;
}
}
//0 1 2 3 4 奇数
//5 6 7 1 10
//0 1 2 3 4 5偶数
//5 6 7 1 10 11
int main()
{
SqList L;
Init_SqList(L);
cout << "//---------顺序表所存数据为奇数---------//" << endl;
L.data[0] = 5;
L.data[1] = 6;
L.data[2] = 7;
L.data[3] = 1;
L.data[4] = 10;
L.length = 5;
for (int i = 0; i < L.length; i++)
cout << L.data[i] << " ";
cout << endl;
//inverse(L);
inverse1(L);
for (int i = 0; i < L.length; i++)
cout << L.data[i] << " ";
cout << endl;
cout << "//---------顺序表所存数据为偶数---------//"<<endl;
L.data[0] = 5;
L.data[1] = 6;
L.data[2] = 7;
L.data[3] = 1;
L.data[4] = 10;
L.data[5] = 11;
L.length = 6;
for (int i = 0; i < L.length; i++)
cout << L.data[i] << " ";
cout << endl;
//inverse(L);
inverse1(L);
for (int i = 0; i < L.length; i++)
cout << L.data[i] << " ";
cout << endl;
return 0;
}