天天看点

用时间空间复杂度为1的算法让顺序表逆置

今天看到一到有意思的题

用时间空间复杂度为1的算法让顺序表逆置

虽然和题意不大对(因为要位置变换,我这种想法不算真正的位置变换)但是感觉很有意思。

其实就是重载运算符

#pragma once
#define MAXSIZE 50

#include<string.h>
template <typename ElemType>
struct Sequence
{
public:
	ElemType data[MAXSIZE];
	int length;
	ElemType& (Sequence::*Index)(int)= &Sequence::IndexR1;

	Sequence(ElemType *A,int size)
	{
		memcpy(data, A,  size * sizeof ElemType);
		length = size;
	}
	bool ReverseIndex(bool t)
	{
		if (t == true)
		{
			Index = &Sequence::IndexR2;
		}
		else
		{
			Index = &Sequence::IndexR1;
		}
		return t;
	}
	ElemType& operator[](int i)
	{
		return (this->*Index)(i);
	}
private:

	ElemType& IndexR1(int i)
	{
		return data[i];
	}

	ElemType& IndexR2(int i)
	{
		return data[length - i - 1];
	}
	/*记:读取成员函数指针需要使用  &Sequence::
		定义函数指针记得给函数名和*加括号
		定义成员函数指针需要在名字的括号里面有 Sequence::
		使用类成员函数指针需要 (this->*Index) 一定要有括号否则优先与右边的括号结合报错,this可以替换成实例里的虚函数等。


	*/
};
	
int main()
{
	int B[] = { 1,2,3,4,5,6,7,8,9,10 };
	Sequence<int> A(B,10);
	cout << A[3];
	A.ReverseIndex(true);
	cout << A[3];
	A.ReverseIndex(false);
	cout << A[3];

}
           

继续阅读