数据结构 - 线性表的顺序实现
《数据结构》严蔚敏
头文件SQlist.h
1 #ifndef SQlist_H_INCLUDED 2 #define SQlist_H_INCLUDED 3 #include<stdio.h> 4 #define OK 1 5 #define ERROR -1 6 #define TRUE 1 7 #define FALSE 0 8 9 #define MAXSIZE 100 /* 存储空间初始分配量 */ 10 #define ListCreaty 10 /* 分配增量 */ 11 typedef int ElemType; /* ElemType类型根据实际情况而定,这里假设为int */ 12 typedef int Status; /* Status是函数的类型,其值是函数结果状态代码,如OK等 */ 13 14 typedef struct 15 { 16 ElemType *data; /* 数组,存储数据元素 */ 17 int length; /* 线性表当前长度 */ 18 int size; /*线性表容量*/ 19 }SqList; 20 Status InitList(SqList&); 21 Status DestoryList(SqList&); 22 Status ListLength(SqList); 23 Status ListEmpty(SqList); 24 Status GetElem(SqList,int, ElemType&); 25 Status InsertSqList(SqList&, int, ElemType); 26 Status FoundElem(SqList, ElemType); 27 Status DeleteList(SqList&, int, ElemType&); 28 void ClearList(SqList&); 29 #endif
函数实现
1 #include"SQlist.h" 2 #include<malloc.h> 3 #include<iostream> 4 using namespace std; 5 /* 初始化顺序线性表 */ 6 Status InitList(SqList&L) 7 { 8 L.data = (ElemType*)malloc(sizeof(ElemType)*MAXSIZE); 9 if (!L.data) 10 { 11 return ERROR; 12 } 13 L.size = MAXSIZE; 14 L.length = 0; 15 return OK; 16 } 17 /*销毁元素*/ 18 Status DestoryList(SqList&L) 19 { 20 if (L.length) 21 { 22 free(L.data); 23 } 24 L.data = NULL; 25 L.length = 0; 26 return OK; 27 } 28 /*清空线性表*/ 29 void ClearList(SqList&L) 30 { 31 L.length = 0; 32 } 33 /*判断为空*/ 34 Status ListEmpty(SqList L) 35 { 36 if (L.length) 37 { 38 return 0; 39 } 40 return 1; 41 } 42 /*插入第i个位置的元素*/ 43 Status InsertSqList(SqList&L, int i, ElemType e) 44 { 45 46 if (i<1 || i>L.length + 1) 47 { 48 cout << "NO" << endl; 49 //return ERROR; 50 } 51 if (L.length > L.size) 52 { 53 ElemType *newbase = (ElemType*)realloc(L.data, sizeof(ElemType) * (L.size+MAXSIZE)); 54 if (!newbase) 55 { 56 return ERROR; 57 } 58 L.data = newbase; 59 L.size += MAXSIZE; 60 } 61 if (L.length != 0) 62 { 63 ElemType *q, *p; 64 q = &L.data[i - 1]; 65 p = &L.data[L.length - 1]; 66 for (; p >= q; p--) 67 { 68 *(p + 1) = *p; 69 } 70 *q = e; 71 L.length++; 72 } 73 else 74 { 75 L.data[L.length] = e; 76 L.length++; 77 } 78 return OK; 79 } 80 Status GetElem(SqList L, int i, ElemType& e) 81 { 82 if (i<0 && i>L.length) 83 return 0; 84 else 85 { 86 e = L.data[i - 1]; 87 } 88 return 1; 89 } 90 Status ListLength(SqList L) 91 { 92 return L.length; 93 } 94 Status FoundElem(SqList L, ElemType e) 95 { 96 int i; 97 for (i = 0; i < L.length; i++) 98 { 99 if (L.data[i] == e) 100 { 101 return i+1; 102 } 103 } 104 return 0; 105 } 106 Status DeleteList(SqList&L, int i, ElemType& e) 107 { 108 if (i<1||i>L.length) 109 { 110 return ERROR; 111 } 112 ElemType *p = &L.data[i - 1]; 113 ElemType *q = L.data + L.length - 1; 114 e = *p; 115 for (; p <= q; p++) 116 { 117 *(p - 1) = *p; 118 } 119 L.length--; 120 return OK; 121 }