线性表有这几个操作:
初始化函数
插入函数
删除函数
展示函数
销毁函数
具体代码如下:
#include
#define MAXSIZE 100
using namespace std;
class List {
private:
int len;
int* data;
public:
//初始化:
void Init() {
len = 0;
data = new int[MAXSIZE];
}
//插入函数
void Insert(int pos,int number) {
//从len-1到pos-1
//移动
for (int i = len-1; i >= pos-1; i–)
{
data[i + 1] = data[i];
}
//赋值
data[pos - 1] = number;
len++;//插入后长度加一
}
//展示函数
void Show() {
if (len > 0) {
cout << “线性表的长度为:” << len << endl;
for (int i = 0; i < len; i++) {
cout << data[i] << “|”;
}
}
//如果线性表已经delete
if (len == -1) {
cout << “线性表已经销毁” << endl;
}
cout << endl;
}
//删除函数
void Delete(int pos, int* number) {
//取删除的值
*number = data[pos - 1];
//移动
for (int i = pos - 1; i < len; i++) {
data[i] = data[i + 1];
}
len–;
}
//释放内存
void Destroy() {
delete[]data;
len = -1;
}
};
int main()
{
List A;
A.Init();
//插入函数
for (int i = 1; i <= 100; i++) {
A.Insert(1,i);
}
A.Show();
int t;
for (int i = 1; i <= 50; i++) {
A.Delete(1, &t);
cout << “Delete:” << t << endl;
}
A.Show();
A.Destroy();
A.Show();
}