数据结构——顺序表的实现

张开发
2026/4/20 11:17:39 15 分钟阅读

分享文章

数据结构——顺序表的实现
#includeiostreamusing namespace std;#define OK 1#define ERROR 0#define OVERFLOW -2typedef int Status; //Status 是函数返回值类型其值是函数结果状态代码。typedef int ElemType; //ElemType 为可定义的数据类型此设为int类型#define MAXSIZE 100 //顺序表可能达到的最大长度typedef struct{ElemType *elem;//存储空间的基地址int length;//顺序表的当前长度}SqList;Status InitList_Sq(SqList L);/*定义一个顺序表的初始化函数 */Status DestroyList_Sq(SqList L); /*定义一个销毁顺序表的函数 */int LocateElem_Sq(SqList L,ElemType e); /*查找值为e的元素*/Status ListInsert_Sq(SqList L,int i,ElemType e); /* 定义一个插入顺序表的函数 */Status ListDelete_Sq(SqList L,int i,ElemType e); /*删除第i个元素*/void DeleteItem(SqList L, int n, ElemType item);Status InitList_Sq(SqList L){ //算法2.1 顺序表的初始化L.elemnew ElemType[MAXSIZE]; //为顺序表分配一个大小为MAXSIZE的数组空间if(!L.elem) exit(OVERFLOW); //存储分配失败L.length0; //空表长度为0return 1;}Status DestroyList_Sq(SqList L){ //算法销毁顺序表if (L.elem){delete []L.elem;L.length 0;}return 1;}ElemType LocateElem_Sq(SqList L,ElemType e){ //算法2.2 顺序表的查找for (int i 0; i L.length; i) {if (L.elem[i] e) {return i 1;}}return 0;}Status ListInsert_Sq(SqList L,int i,ElemType e){ //算法2.3 顺序表的插入if (i 1 || i L.length 1 || L.length MAXSIZE) {return ERROR;}for (int j L.length; j i; j--) {L.elem[j] L.elem[j - 1];}L.elem[i - 1] e;L.length;return 1;}Status ListDelete_Sq(SqList L,int i,ElemType e){ //算法2.4 顺序表的删除if (i 1 || i L.length) {return ERROR;}e L.elem[i - 1];for (int j i; j L.length; j) {L.elem[j - 1] L.elem[j];}L.length--;return 1;}int main(){SqList L;int i,res,temp,a,b,c,e,choose;//a代表插入的位置b代表插入的数值,c代表要删//除数的位置,e代表所要查找的数值cout1. 建立顺序表\n;cout2. 输入数据\n;cout3. 查找\n;cout4. 插入\n;cout5. 删除\n;cout6. 输出数据\n;cout7. 销毁顺序表\n;cout0. 退出\n\n;choose-1;while(choose!0){cout请选择:;cinchoose;switch(choose){case 1:if(InitList_Sq(L)) //创建顺序表cout成功建立顺序表\n\n;elsecout顺序表建立失败\n\n;break;case 2: //输入10个数cout请输入10个数:\n;for(i0;i10;i)cinL.elem[i];L.length10;coutendl;break;case 3: //顺序表的查找cout 请输入要查找的元素:\n;cin e;a LocateElem_Sq(L, e); // 补全参数if (a ! 0)cout 找到元素位置为 res endl endl;elsecout 未找到该元素\n\n;break;case 4: //顺序表的插入cout请输入你要插入的第i个元素和其数值eendl;cinie;if(ListInsert_Sq(L,i,e)) cout插入成功\nendl;else cout插入失败endl;case 5: //顺序表的删除cout 请输入要删除的位置i:\n;cin i; // 删除多余的endl和ee是输出参数if (ListDelete_Sq(L, i, e))cout 删除成功被删除元素为 e \n\n;elsecout 删除失败位置不合法\n\n;break;case 6: //顺序表的输出cout 当前顺序表为:\n;for (i 0; i L.length; i) {cout L.elem[i] ;}cout endl endl;break;case 7: //销毁顺序表if (DestroyList_Sq(L))cout 成功销毁顺序表\n\n;elsecout 销毁失败\n\n;break;}}return 0;}

更多文章