顺序表的实现 2021/9/19
顺序表的实现



#include<iostream> #include<string> #include<iomanip> #include <cstdlib> using namespace std; #define OVERFLOW -2 typedef int ElemType; //ElemType 为可定义的数据类型,此设为int类型 #define MAXSIZE 100 //顺序表可能达到的最大长度 typedef struct { ElemType *elem; //存储空间的基地址 int length; //当前长度 } SqList; void InitList_Sq(SqList &L) { //算法2.1 顺序表的初始化 //构造一个空的顺序表L L.elem = new ElemType[MAXSIZE]; //为顺序表分配一个大小为MAXSIZE的数组空间 if (!L.elem) exit(OVERFLOW); //存储分配失败退出 L.length = 0; //空表长度为0 } /* 请在这里填写答案 */ int GetElem(SqList L, int i, ElemType &e)//顺序表的取值 { if (i<1||i>L.length) return 0; e = L.elem[i-1]; return 1; } int LocateElem_Sq(SqList L, double e)//顺序表的查找 { int i; for (i = 0;i<L.length; i++) if(L.elem[i] == e) return i+1; return 0; } int ListInsert_Sq(SqList &L, int i, ElemType e)//顺序表的插入 { if (i<1||(i>L.length+1)) return 0; if (i>= MAXSIZE) return 0; int j; for (j=L.length+1;j>i;j--) { L.elem[j-1]= L.elem[j-2]; } L.elem[i-1] = e; ++L.length; return 1; } int ListDelete_Sq(SqList &L, int i)//顺序表的删除 { if (i<1||i>L.length) return 0; int j; for(j=i;j<=L.length;j++) { L.elem[j-1]= L.elem[j]; --L.length; return 1; } } void ListInput(SqList &L)//顺序表数据的输入 { int j; cin>>j; if(j==0) { cout<<"顺序表为空"<<endl; } for(int i = 0;i<j;i++) { cin>>L.elem[i]; L.length++; } } void ListOutput(SqList L)//顺序表数据的输出 { int i; for(i = 0;i<L.length;i++) { cout <<L.elem[i]<<" "; } cout<<endl; } int main() { SqList L; int i = 0, temp, a, c; double price; ElemType e; //初始化线性表 InitList_Sq(L); //输入线性表 ListInput(L); //输出线性表 ListOutput(L); //顺序表取值 cin>>i; temp = GetElem(L, i, e); if (temp != 0) { cout <<"查找位置的数是"<<e<< endl; } else cout << "查找失败!位置超出范围\n"; //顺序表查找 cin >> price; temp = LocateElem_Sq(L, price); if (temp != 0) { cout << "该数位置为" << temp << endl; } else cout << "查找失败!\n"; //顺序表的插入 cin >> a; cin >> e; //输入a和e,a代表插入的位置,e代表插入的数值 if (ListInsert_Sq(L, a, e)) ListOutput(L); else cout << "插入失败\n"; //顺序表的删除 cin >> c; if (ListDelete_Sq(L, c)) ListOutput(L); else cout << "删除失败\n"; return 0; }


浙公网安备 33010602011771号