本文共 1857 字,大约阅读时间需要 6 分钟。
线性表的顺序存储:指在内存中用地址连续的一块存储空间顺序存放线性表的各元素,用这种存储形式存储的线性表称其为顺序表。因为内存中的地址空间是线性的,因此,用物理上的相邻实现数据元素之间的逻辑相邻关系是既简单,又自然的。
//顺序表存储结构定义typedef int ElemType;#define maxSize 100typedef struct tagSeqList{ ElemType data[maxSize]; int length; tagSeqList() { memset(data, 0, sizeof(ElemType)*maxSize); length = 0; //或者初始化使用 //memset(this, 0, sizeof(tagSeqList)); }}SeqList;void print(SeqList L){ printf("current seql length is %d\n", L.length); for (int i = 0; i < L.length; i++) { printf("%d\t", L.data[i]); } printf("\n");}//插入操作int Insert(SeqList& L, int index, ElemType x){ //判断初始数组长度和插入位置的合法性 if (L.length >= maxSize) //这里是>= 不是> { printf("data flow\n"); return -1; } if (index<1 || index>L.length + 1) { printf("wrong position\n"); return -1; } //从后往前 for (int i = L.length; i >= index; i--) L.data[i] = L.data[i-1]; L.data[index - 1] = x; L.length++; return 1;}//删除操作int Delete(SeqList& L, int index, ElemType& value){ //没有判断长度为0 if (L.length == 0) { printf("under flow\n"); return -1; } if (index<1 || index>L.length) { printf("invalid index \n"); return -1; } value = L.data[index - 1]; for (int i = index - 1; i < L.length-1; i++) { L.data[i] = L.data[i+1]; } //modify length L.length--; return 1;}/***查找操作*///按位查找int Get(SeqList L, int index,ElemType& value){ if (index<1 || indexL.length) printf("invalid index\n"); for (int i = 0; i < (to - from + 1) / 2; i++) { swap(L.data[from + i], L.data[to - i]); }}void Converse(SeqList&L, int n, int k)//循环左移k{ Reverse(L, 0, k - 1); Reverse(L, k , n - 1); Reverse(L, 0, n - 1);}int _tmain(int argc, _TCHAR* argv[]){ SeqList L ; //Insert(L, 0, 2); Insert(L, 1, 1); Insert(L, 2, 3); Insert(L, 3, 7); Insert(L, 4, 8); /*ElemType value; Delete(L, 2, value); int index; Locate(L, 5, index); printf("index=%d", index);*/ print(L); //Reverse(L); Converse(L, L.length, 1); print(L); getchar(); return 0;}
转载地址:http://tiown.baihongyu.com/