#include <stdio.h>
#include <stdlib.h>//morall free函数
#include <iostream>
#define elemType int
#define LIST_INIT_SIZE 10
using namespace std;
struct sqlist {
elemType* elem;//数组
int size= LIST_INIT_SIZE;//容量
int length;//长度
};
//初始化
void initsqlist(sqlist& list) {
list.elem = new elemType[LIST_INIT_SIZE];
//上下两句语句等价
//list.elem=(int*) malloc(5*sizeof(int));
list.size = LIST_INIT_SIZE;
list.length = 0;
//初始化一个数组{1,2,3,4,5}
for (int i = 0; i < 5; i++) {
list.elem[i] = i + 1;
list.length++;
}
}
//查询
void rlist(sqlist list) {
for (int i = 0; i < list.length; i++) {
cout << "list数组中第" << i + 1 << "个元素的值为" << list.elem[i] << endl;
}
}
//插入
void insertlist(sqlist& list, int pos, elemType val) {
for (int i = list.length-1; i >=pos-1; i--){
list.elem[i+1 ] = list.elem[i];
//从最后一个元素开始,依次向后移动一个位置
}
list.elem[pos - 1] = val;
list.length++;
}
//删除
void deletelist(sqlist& list, int pos, elemType &deleteval) {
deleteval = list.elem[pos - 1];
for (int i = pos-1; i < list.length;i++){
list.elem[i] = list.elem[i + 1];
//从删除的元素开始,依次向前移动一个位置
}
list.length--;
}
int main() {
sqlist list;
initsqlist(list);
insertlist(list, 3, 99);
insertlist(list, 1, 99);
rlist(list);
elemType deleteval;
deletelist(list, 4, deleteval);
rlist(list);
return 0;
}在这里插入代码片
效果图