先写类(模板内容复习)
#include <iostream>
using namespace std;
template <class elem>
class list
{
public:
virtual bool insert(elem x) = 0;
virtual bool append(elem x) = 0;
virtual bool remove(elem& x) = 0;
virtual void prev() = 0;
virtual void next() = 0;
};
template <class elem>
class alist :public list <elem>
{
private:
int max;
int now;
int thismax;
elem* point;
public:
alist(int a=10)
{
max = a;
now = thismax = 0;
point = new elem[a];
}
~alist() { delete[]point; }
bool insert(elem x)
{
if (now >= max || now<0 || now>thismax - 1)return false;
else
{
int i;
for (i = thismax; i>now; i--)point[i] = point[i - 1];
thismax++;
}
point[now] = x;
return true;
}
bool append(elem x)
{
if (thismax >= max)return false;
point[thismax++] = x;
return true;
}
bool remove(elem &x)
{
if (thismax=0||now < 0 || now >= thismax)return false;
else
{
x = point[now];
int i = now;
for (; i<thismax-1; i++)point[i] = point[i + 1];
thismax--;
}
return true;
}
void prev() { if (now > 0)now--; }
void next() { if (now < thismax - 1) now++; }
};
在主函数里写内容,加深理解。
int main()
{
class alist <int>stu;
stu.insert(5);
cout << stu.append(6)<<endl;
int rem;
stu.next();
stu.remove(rem);
cout << rem;
return 0;
}
运行后:
1
6
注意:
要写明class alist <int>stu;中的<int>,它用来对应前面的<elem>。