顺序表是最简单的数据结构之一。常见的操作就是建表、增删改查。
采用顺序存储结构,也就是数组,这样随机存取。
增删需要移动大量元素,时间复杂度O(n)。
顺序查找的时间复杂度也是O(n),不过谁会那么傻,通常都先排序一遍,然后二分查找。
代码很简单,基本就是严蔚敏那本书,可以参照着看。
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
// 顺序表的实现
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define OVERFLOW 1
typedef int ElemType;
typedef bool Status;
#define OK true;
#define FAIL false;
typedef struct {
ElemType *elem;
int length;
int listSize;
}SqList;
Status InitList(SqList &L) {
L.elem = (ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem)
exit(OVERFLOW);
L.length = 0;
L.listSize = LIST_INIT_SIZE;
return OK;
}
Status CreateList(SqList &L, ElemType* data, int size) {
for(int i=0; i<size; i++) {
L.elem[i] = data[i];
L.length++;
}
return OK;
}
// index不是下标,是第几个
Status GetElem(SqList L, int i, ElemType &e) {
if(i<1 || i>L.length)
return false;
e = L.elem[i-1];
return OK;
}
// 其实就是遍历顺序表,效率低下,按值查找通常要先排序
int LocateElem(SqList L, ElemType x) {
for(int i=0; i<L.length; i++)
if(L.elem[i] == x)
return i+1;
return -1; // 没找到
}
Status ListInsert_Sq(SqList &L, int i, ElemType e) {
if(i<1 || i>L.length+1)
return FAIL;
if(L.length == L.listSize) {
ElemType* newBase = (ElemType*)realloc(L.elem, (LIST_INIT_SIZE + LISTINCREMENT) * sizeof(ElemType));
printf("new space\n");
if(!newBase)
exit(OVERFLOW);
L.elem = newBase;
L.listSize += LISTINCREMENT;
}
for(int j=L.length-1; j>=i-1; j--)
L.elem[j+1] = L.elem[j];
L.elem[i-1] = e;
L.length++;
return OK;
}
Status ListDelete_Sq(SqList &L, int i, ElemType &e) {
if(i<1 || i>L.length)
return FAIL;
e = L.elem[i-1];
for(int j=i; j<=L.length-1;j++)
L.elem[j-1] = L.elem[j];
L.length--;
return OK;
}
void print(SqList L) {
cout<<"输出顺序表"<<endl;
printf("Sqlist size: %d\n", L.length);
for(int j=0; j<=L.length-1; j++)
printf("%d\t", L.elem[j]);
cout<<endl;
}
void DestroyList(SqList &L) {
if(L.elem) {
printf("\n\ndestroy list\n");
delete[] L.elem;
}
L.elem = NULL;
}
int main() {
ElemType testCase[] = {
6501,6828,6963,7036,7422,7674,8146,8468,8704,8717,9170,9359,9719,9895,9896,9913,9962,154,293,334,492,1323,
1479,1539,1727,1870,1943,2383,2392,2996,3282,3812,3903,4465,4605,4665,4772,4828,5142,5437,5448,5668,5706,
5725,6300,6335
};
int size = sizeof(testCase) / sizeof(ElemType);
SqList myL;
InitList(myL);
print(myL);
CreateList(myL, testCase, size);
print(myL);
printf("\nget element by index\n");
for(int i=1; i<=size; i++) {
int e;
GetElem(myL, i, e); // i是第几个,不是数组下标
printf("%d: %d\t", i, e);
}
printf("\n\nget location of element\n");
printf("index: %d\n", LocateElem(myL, 12));
printf("index: %d\n", LocateElem(myL, 9913));
printf("\n\ninsert element\n");
ListInsert_Sq(myL, 5, 10);
print(myL);
for(int i=0; i<100; i++)
ListInsert_Sq(myL, 5, i);
print(myL);
printf("\n\n删除性测试\n");
ElemType e;
for(int i=1; i<=5; i++) {
ListDelete_Sq(myL, i, e); // i是第几个,不是数组下标
printf("e: %d\n", e);
print(myL);
}
DestroyList(myL);
return 0;
}