顺序表的操作
#include<iostream>
using namespace std;
#define MaxSize 20
typedef struct {
int* data;
int length;
}seqlist;
void InitList(seqlist &L) {
L.data = new int[MaxSize];
L.length = 0;
cout << "线性表分配空间是:" << MaxSize << endl;
cout << "线性表的当前长度是" << L.length << endl;
}
void InsertList(seqlist& L, int i, int e) {
if (L.length >= MaxSize) return;
if (i > L.length + 1) return;
for (int j = L.length; j >= i; j--) {
L.data[j] = L.data[j - 1];
}
L.data[i - 1] = e;
L.length++;
cout << "插入成功" << endl;
}
void ErgodicList(seqlist& L) {
cout << "链表元素是:" << endl;
for (int i = 0; i < L.length; i++) {
cout << L.data[i] << endl;
}
cout << "链表元素长度是:"<< L.length << endl;
}
void ListDelete(seqlist& L, int i, int& e ) {
if (i < 1 || i > L.length) return;
e = L.data[i - 1];
for (int j = i; j < L.length; j++) {
L.data[j - 1] = L.data[j];
}
L.length--;
return;
}
int main() {
seqlist L;
cout << "请选择:" << endl;
cout << "---------------------------------------------" << endl;
cout << "1:初始化 2:插入 3:遍历 4:删除 " << endl;
cout << "5: 6: 7: 9:退出 " << endl;
cout << "---------------------------------------------" << endl;
int ci;
cin >> ci;
if(ci == 1)
InitList(L);
while (ci != 9) {
cout << "请选择:" << endl;
cin >> ci;
if (ci == 2) {
cout << "请输入插入的位置" << endl;
int i;
cin >> i;
cout << "请输入插入的数字" << endl;
int e;
cin >> e;
InsertList(L,i, e);
}
if (ci == 3) ErgodicList(L);
if (ci == 4) {
cout << "请输入需要删除的位置" << endl;
int i;
int e;
cin >> i;
ListDelete(L, i, e);
cout << "您删除的" << i << "位置的元素是:" << e << endl;
}
}
cout << "成功退出" << endl;
}