顺序表
注意:元素位序为1,数组元素下标为0
#include <iostream> using namespace std; #define MaxSize 50 typedef struct SqList { int *data; int length; } SqList; void InitList(SqList &L); int Length(SqList L); // 按值查找(返回第一个元素值等于e的元素位序) int LocateElem(SqList L, int e); // 按位查找操作 int GetElem(SqList L, int a); bool ListInsert(SqList &L, int a, int e); int ListDelete(SqList &L, int a); void PrintList(SqList L); bool Empty(SqList L); void DestroyList(SqList &L); int main() { SqList SL; InitList(SL); ListInsert(SL, 1, 10); ListInsert(SL, 2, 9); ListInsert(SL, 3, 8); ListInsert(SL, 4, 7); PrintList(SL); ListDelete(SL, 1); cout << "delete idx 1" << endl; PrintList(SL); cout << "Locate elem:" << LocateElem(SL, 9) << endl; cout << "Get elem:" << GetElem(SL, 2) << endl; cout << "SL length:" << Length(SL) << endl; cout << "IS empty:" << Empty(SL) << endl; DestroyList(SL); return 0; } void InitList(SqList &L) { L.data = new int[MaxSize]; L.length = 0; } int Length(SqList L) { return L.length; } int LocateElem(SqList L, int e) { for (int i = 0; i < L.length; ++i) { if (L.data[i] == e) { return i + 1; } } return -1; } int GetElem(SqList L, int a) { return L.data[a - 1]; } bool ListInsert(SqList &L, int a, int e) { if (a < 1 || a > L.length + 1) { cout << "Illegal insertion position" << endl; return false; } if (L.length >= MaxSize) { return false; } for (int i = L.length; i >= a; i--) { L.data[i] = L.data[i - 1]; } L.data[a - 1] = e; L.length++; return true; } int ListDelete(SqList &L, int a) { if (a < 1 || a > L.length) { cout << "Illegal delete position" << endl; return -1; } if (L.length < 1) { return -1; } int deletedElem = L.data[a - 1]; for (int i = a; i < L.length; ++i) { L.data[i - 1] = L.data[i]; } L.length--; return deletedElem; } void PrintList(SqList L) { for (int i = 0; i < L.length; ++i) { cout << L.data[i] << " "; } cout << endl; } bool Empty(SqList L) { if (L.length == 0) { return true; } return false; } void DestroyList(SqList &L) { delete[]L.data; L.data = NULL; cout << "memory free" << endl; }