标签:open struct str 16px 断线 pen typedef 顺序表 空间
顺序表基本运算
顺序表存储密度大、存储空间利用率高
可以通过序号之间访问任何元素,即随机存取
插入和删除时由于要移动大量的元素,耗费时间,时间复杂度为O(n^2)
具体算法如下:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #define MaxSize 50 4 typedef int ElemType; 5 6 typedef struct { 7 ElemType data[MaxSize]; 8 int length; 9 } SqList; 10 11 /*创建顺序表*/ 12 void CreateList(SqList* &L, ElemType a[], int n) { 13 int i; 14 L = (SqList *)malloc(sizeof(SqList)); 15 for (i = 0; i < n; i++) { 16 L -> data[i] = a[i]; 17 } 18 L -> length = n; 19 } 20 21 /*基本运算*/ 22 /*初始化线性表 InitList(L)*/ 23 void InitList(SqList* &L) { 24 L = (SqList *)malloc(sizeof(SqList)); 25 L -> length = 0; 26 } 27 28 /*销毁线性表 DestoryList(L)*/ 29 void DestoryList(SqList* &L) { 30 free(L); 31 } 32 33 /*判断线性表是否为空 ListEmpty(L)*/ 34 int ListEmpty(SqList *L) { 35 return L -> length == 0; 36 } 37 38 /*求线性表的长度 ListLength(L)*/ 39 int ListLength(SqList *L) { 40 return L -> length; 41 } 42 43 /*输出线性表 DispList(L)*/ 44 void DispList(SqList *L) { 45 int i; 46 for (i = 0; i < L -> length; i++) { 47 printf("%d ", L -> data[i]); 48 } 49 printf("\n"); 50 } 51 52 /*求线性表中某个数据元素值 GetElem(L, i, e)*/ 53 bool GetElem(SqList *L, int i, ElemType &e) { 54 if (i < 1 || i > L -> length) { 55 return false; 56 } 57 e = L -> data[i - 1]; 58 return true; 59 } 60 61 /*按元素值查找 LocateElem(L, e)*/ 62 int LocateElem(SqList *L, ElemType e) { 63 int i = 0; 64 while(i < L-> length && L -> data[i] != e) { 65 i++; 66 } 67 if (i > L -> length) { 68 return 0; 69 } else { 70 return i + 1; 71 } 72 } 73 74 /*插入数据元素 ListInsert(L, i, e)*/ 75 bool ListInsert(SqList* &L, int i, ElemType e) { 76 if (i < 1 || i > L -> length) { 77 return false; 78 } 79 int k; 80 i--; 81 for (k = L -> length - 1; k >= i; k--) { 82 L -> data[k + 1] = L -> data[k]; 83 } 84 L -> data[i] = e; 85 L -> length++; 86 return true; 87 } 88 89 /*删除数据元素 ListDelete(L, i, e)*/ 90 bool ListDelete(SqList* &L, int i, ElemType &e) { 91 if (i < 1 || i > L -> length) { 92 return false; 93 } 94 i--; 95 e = L -> data[i]; 96 int k; 97 for(k = i; k < L -> length; k++) { 98 L -> data[k] = L -> data[k + 1]; 99 } 100 L -> length--; 101 return true; 102 } 103 104 int main(int argc, char const *argv[]) { 105 int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; 106 SqList *L; 107 CreateList(L, a, 9); 108 DispList(L); 109 ElemType e; 110 GetElem(L, 4, e); 111 printf("the fourth number : %d\n", e); 112 printf("number eight : %d\n", LocateElem(L, 8)); 113 printf("insert 10 on the 8th\n"); 114 ListInsert(L, 8, 10); 115 DispList(L); 116 printf("delete 8th number:\n"); 117 ListDelete(L, 8, e); 118 DispList(L); 119 DestoryList(L); 120 return 0; 121 }
运行结果在这儿*^_^*
1 2 3 4 5 6 7 8 9 the fourth number : 4 number eight : 8 insert 10 on the 8th 1 2 3 4 5 6 7 10 8 9 delete 8th number: 1 2 3 4 5 6 7 8 9
标签:open struct str 16px 断线 pen typedef 顺序表 空间
原文地址:https://www.cnblogs.com/flow-wangqi/p/9513180.html