数据结构学习-第一天
初始化一个顺序表:
typedef struct{
Elemtype date[MAXSIZE];
int length;
}SeqList;
void InitList(SeqList *L){
L->length=0;
}//初始化顺序表
输出:
int main(int argc,char const *argv[]){
SeqList list;
InitList(&list);
return 0;
}
给顺序表添加数据:
void CreatElem(SeqList *L) {
int n;
cout << "请输入顺序表的长度: ";
cin >> n;
if (n > MAXSIZE) {
cout << "超出最大容量!" << endl;
return;
}
L->length = n;
cout << "请输入" << n << "个元素: ";
for (int i = 0; i < L->length; i++) {
cin >> L->date[i];
}
}
输出:
int main(int argc,char const *argv[]){
SeqList list;
InitList(&list);
CreatElem(&list);
return 0;
}
删除指定位置元素:
void DelElem(SeqList* L, int pos, Elemtype* e) {
if (pos < 1 || pos > L->length) {
cout << "删除位置错误" << endl;
return;
}
*e = L->data[pos - 1];
if (pos < L->length) {
for (int i = pos; i < L->length; i++) {
L->data[i - 1] = L->data[i];
}
L->length--;
}
}
输出:
int main(int argc,char const *argv[]){
SeqList list;
InitList(&list);
CreatElem(&list);
int n;
cout <<"你想删除哪个位置的元素: ";
cin >> n;
Elemtype delDate;
deleteElem(&list,n,&delDate);
printf("被删除的数据为:%d\n",delDate);
return 0;
}
顺序表整个的输出函数:
void listElem(SeqList* L) {
for (int i = 0; i < L->length; i++) {
cout << L->data[i]<<' ';
}
cout << endl;
}
全部输出:
int main(int argc, char const* argv[]) {
SeqList list;
IniList(&list);
CreateElem(&list);
int count;
cout << "你想执行什么操作" << endl;
cout << "删除指定位置元素:1" << endl;
cin >> count;
if (count == 1) {
int pos;
Elemtype DelData;
cout << "你想删除什么位置的元素:";
cin >> pos;
DelElem(&list, pos, &DelData);
cout << "删除的元素是:" << DelData << endl;
cout << "删除指定元素后的顺序表:" << endl;
listElem(&list);
}
return 0;
}
插入指定元素:
void InsertElem(SeqList* L, int pos, Elemtype e) {
if (L->length >= MAXSIZE) {
cout << "顺序表已经满了" << endl;
return;
}
if (pos < 1 || pos > L->length + 1) {
cout << "插入位置错误" << endl;
return;
}
if (pos <= L->length) {
for (int i = L->length - 1; i >= pos - 1; i--) {
L->data[i + 1] = L->data[i];
}
L->data[pos - 1] = e;
L->length++;
}
}
全部输出:
int main(int argc, char const* argv[]) {
SeqList list;
IniList(&list);
CreateElem(&list);
int count;
cout << "你想执行什么操作" << endl;
cout << "删除指定位置元素:1" << endl;
cout << "插入指定位置元素:2" << endl;
cin >> count;
if (count == 1) {
int pos;
Elemtype DelData;
cout << "你想删除什么位置的元素:";
cin >> pos;
DelElem(&list, pos, &DelData);
cout << "删除的元素是:" << DelData << endl;
cout << "删除指定元素后的顺序表:" << endl;
listElem(&list);
}
if (count == 2) {
int pos;
Elemtype InsertData;
cout << "你想插入什么位置:";
cin >> pos;
cout << "该位置插入什么元素:";
cin >> InsertData;
InsertElem(&list, pos, InsertData);
cout << "插入指定元素后的顺序表:" << endl;
listElem(&list);
}
return 0;
}