#include<iostream>
using namespace std;
#define MAXSIZE 100
template<typename EleType>
class StaticList
{
public:
typedef struct
{
EleType data;
int cur;
}Node;
StaticList();
~StaticList(){}
bool Insert(const EleType& e, int index = 1);
bool Delete( EleType& e, int index = 1);
void Show()const;
private:
int NewSpace();
void DeleteSpace(int index);
bool Empty()const;
bool Full()const;
Node StList[MAXSIZE];
int Length;
};
template<typename EleType>
StaticList<EleType>::StaticList() :Length(0)
{
for (int i = 0; i < MAXSIZE - 1;++i)
{
StList[i].cur = i + 1;
}
StList[MAXSIZE - 1].cur = 0;
}
template<typename EleType>
bool StaticList<EleType>::Insert(const EleType& e, int index /*= 1*/)
{
if (Full())
{
cout << "Can't insert element to a full List!\n";
return false;
}
if (index<1||index>Length+1)
{
cout << "The invalid index!\n";
return false;
}
int k = NewSpace();
int j = MAXSIZE - 1;
if (k)
{
StList[k].data = e;
for (int i = 1; i <= index - 1;++i)
{
j = StList[j].cur;
}
StList[k].cur = StList[j].cur;
StList[j].cur = k;
++Length;
return true;
}
return false;
}
template<typename EleType>
bool StaticList<EleType>::Delete(EleType& e, int index )
{
if (Empty())
{
cout << "Can't delete element in a empty list!\n";
return false;
}
if (index<1 || index>Length )
{
cout << "The invalid index!\n";
return false;
}
int k = MAXSIZE - 1;
int i = 1;
for (; i <= index - 1;++i)
{
k = StList[k].cur;
}
i = StList[k].cur;
StList[k].cur = StList[i].cur;
e = StList[i].data;
DeleteSpace(i);
--Length;
return true;
}
template<typename EleType>
void StaticList<EleType>::Show() const
{
if (Empty())
{
cout << "The List is Empty!\n";
return;
}
int k = StList[MAXSIZE - 1].cur;
cout << "学生成绩如下:\n";
for (int i = 1; i <= Length;++i)
{
cout<<"第"<<i<<"个学生的成绩:";
cout << StList[k].data << endl;
k = StList[k].cur;
}
cout << endl;
}
template<typename EleType>
bool StaticList<EleType>::Full() const
{
if (Length > MAXSIZE - 2)
{
return true;
}
return false;
}
template<typename EleType>
bool StaticList<EleType>::Empty() const
{
return(Length == 0);
}
template<typename EleType>
void StaticList<EleType>::DeleteSpace(int index)
{
StList[index].cur = StList[0].cur;
StList[0].cur = index;
}
template<typename EleType>
int StaticList<EleType>::NewSpace()
{
int i = StList[0].cur;
if (StList[0].cur)
{
StList[0].cur = StList[i].cur;
}
return i;
}
int main()
{
StaticList<int> TestList;
TestList.Insert(99,1);
TestList.Insert(90,2);
TestList.Insert(95,3);
TestList.Insert(80,4);
TestList.Insert(100,5);
TestList.Show();
cout<<"在第4个位子插入成绩70后"<<endl;
TestList.Insert(70,4);
TestList.Show();
int m=90;
TestList.Delete(m,2);
cout << "删除第2个位子的成绩" << m << "后"<<endl;
TestList.Show();
return 0;
}