线性表之顺序表
线性表的结构体定义:
#define MaxSize 100 typedef struct { int data[MaxSize]; int length; }Sqlist;
顺序表在内存中以数组形式保存,是一组连续的内存空间。
顺序表基本算法:
构造一个空的线性表:
//初始化线性表 STATUS InitList(Sqlist &L) { //置表长为0 L.length = 0; return OK; }
返回指定元素位置:
//定义返回线性表中某个元素的位置i int LocateElem(Sqlist L, int x) { int i; for (i = 0; i < L.length; i++) { if (x < L.data[i]) //返回元素位置 return i; } //没有元素比x大,则应该是第一个位置 return i; }
创建一个线性表:
//创建线性表 STATUS CreateList(Sqlist &L, int data[], int size) { if (size > MaxSize) return ERROR; int i = 0; for (i = 0; i < size; i++) { L.data[i] = data[i]; } L.length = size; return OK; }
插入一个元素(假设线性表中元素已升序排序)
//插入x后移动相应的元素位置,假设插入总能成功 STATUS InsertElem(Sqlist &L, int x) { int positionOfX, i; int sum = L.length; positionOfX = LocateElem(L, x); for (i = L.length - 1; i >= positionOfX; i--) { L.data[i+1] = L.data[i]; } L.data[positionOfX] = x; L.length++; //判断是否插入成功 if (L.length > sum) { return OK; } else return ERROR; }
删除指定位置的元素:
//删除指定位置的元素,并将删除元素返回 int DeleteElemAtPos(Sqlist &L, int p) { if (p<0 || p>L.length-1) return ERROR; int result = L.data[p]; int i; //注意是i<L.length-1,而不是<L.length for (i = p; i < L.length-1; i++) { L.data[i] = L.data[i + 1]; } --L.length; return result; }
在指定位置插入元素:
//在指定位置p插入元素 STATUS InsertElemAtPos(Sqlist &L, int p, int x) { if (p<0 || p>L.length || L.length == MaxSize) return ERROR; int i = 0; for (i = L.length - 1; i >= p; i--) { L.data[i + 1] = L.data[i]; } L.data[p] = x; L.length++; return OK; }
给线性表元素升序排序(可使用多种排序算法,本文使用冒泡):
//给线性表排序 STATUS SortList(Sqlist &L) { int i, j; int temp = 0; for(i=L.length-1;i>=1;i--) for (j = 0; j <= i-1; j++) { if (L.data[j] > L.data[j + 1]) { temp = L.data[j]; L.data[j] = L.data[j + 1]; L.data[j + 1] = temp; } } return OK; }
测试代码:
int main() { //创建一个新表 Sqlist *A; A = (Sqlist*)malloc(sizeof(Sqlist)); cout << "Initial Sqlist" << endl; InitList(*A); cout << "A的长度 " << A->length << endl << endl; int data[5] = { 1,3,2,3,5 }; CreateList(*A, data, 5); cout << "length of A is " << A->length << endl; cout << "初始化后的线性表A是:" << endl; PrintList(*A); cout << endl; cout << "给线性表排序之后是:" << endl; SortList(*A); PrintList(*A); cout << endl; cout << "插入一个元素后的列表" << endl; InsertElem(*A, 2); PrintList(*A); cout << "length of A is :" << A->length << endl << endl; cout << "插入元素0" << endl; InsertElem(*A, 0); PrintList(*A); cout << "length of A is " << A->length << endl << endl; cout << "after Delete elem 3 " << endl ; DeleteElemAtPos(*A, LocateElem(*A, 3)); PrintList(*A); cout << "length of A is " << A->length << endl; //解决显示窗口一显而过 system("pause"); return 0; }