类成员
创建一个数组类,类的成员属性有数组、数组的长度和数组的容量
class seqList
{
public:
int length;
int capacity;
int *arr=new int[capacity];
void Init(seqList& l);
void Push();
void Show();
void Insert();
void Pop();
void Delete();
};
成员函数是实现线性表的各种功能
初始化
线性表的初始化需要定义其容量,并将数组长度初始化为0
void seqList::Init(seqList& l)
{
l.length = 0;
l.capacity = 100;
}
尾插
在数组末尾插入新的数据,插入完成后将线性表的长度+1
但若该线性表已满,即this->length==this->capacity则插入失败。我懒得写了,就不写了
void seqList::Push()
{
cout << "piz input the ele" << endl;
int x = 0;
cin >> x;
this->arr[this->length] = x;
this->length++;
cout << "push completed!" << endl;
system("pause");
}
显示
本质就是遍历,然后打印
void seqList::Show()
{
for (int i = 0; i < this->length; i++)
{
cout << this->arr[i] << " ";
}
cout << endl;
}
插入
插入的目的是可以选择插到哪里,比尾插更灵活
输入合理的位置pos后,将线性表长度+1,遍历pos之后的数据,将每个数据往后移一个,最后将新的数据放在pos上
void seqList::Insert()
{
int pos = 0;
int x = 0;
cout << "plz input pos u want to insert" << endl;
cin >> pos;
cout << "plz input x u want to insert" << endl;
cin >> x;
if (pos > this->length || pos < 0)
{
cout << "no such pos! " << endl;
}
else
{
this->length++;
for (int i = this->length; i > pos-1; i--)
{
cout << i;
this->arr[i] = this->arr[i-1];
}
this->arr[pos-1] = x;
cout << "insert completed!" << endl;
system("pause");
}
}
尾删
将线性表长度-1即可
void seqList::Pop()
{
this->length--;
cout << "pop completed!" << endl;
system("pause");
}
删除
可指定值删除
输入存在的值后遍历数组直到查找到
当然也有找不到的情况,就是输入不存在的值,这种情况直接返回就好,我懒得写了
记得最后把长度-1
void seqList::Delete()
{
int x = 0;
cout << "plz input x u want to delete" << endl;
cin >> x;
for (int i = 0; i < this->length; i++)
{
if (this->arr[i] == x)
{
for (; i < this->length; i++)
{
this->arr[i] = this->arr[i + 1];
}
}
}
this->length--;
cout << "delete completed!" << endl;
system("pause");
}
实现
通过创建一个对象,通过该对象实现各种操作
seqList v;
可直接在main函数调用,也可通过switch选择