顺序映象:以 x 的存储位置和 y 的存储位置之间某种关系表示逻辑关系<x,y>。
最简单的一种顺序映象方法是:令 y 的存储位置和 x 的存储位置相邻。
顺序映像的 C 语言描述:
顺序表的存储结构定义
- #define MAXSIZE 100
- // 线性表存储空间的分配量,即数组长度
- typedef struct
- {
- ElemType elem[MAXSIZE];
- int length; // 当前长度
- } SqList; // 俗称 顺序表
创建并初始化为空表
- Status InitList(SqList &L)
- {
- // TODO (#1#): 创建空表
- L.length=0;
- return OK;
- //-------------------------------------
- }
将表L置空
- Status ClearList(SqList &L)
- {
- // TODO (#1#): 清空表
- L.length=0;
- return OK;
- //-------------------------------------
- }
求表L的长度
- int ListLength(SqList L)
- {
- // TODO (#1#): 求顺序表长度
- return L.length;
- //-------------------------------------
- }
在表L中定位元素e首次出现的位置. 操作成功返回位序,失败时返回0
compare(a,b) 为比较函数,匹配时返回true,否则返回false
- int LocateElem(SqList L, ElemType e, bool (*compare)(ElemType,ElemType))
- {
- // TODO (#1#): 在表中定位元素e,用compare(a,b)匹配元素
- for (int j=0; j<L.length; j++)
- if ( compare(L.elem[j],e) ) return j;
- return 0;
- //-------------------------------------
- }
在表L中插入第i个元素e. 操作成功返回OK,失败时返回ERROR
- Status ListInsert(SqList &L, int i, ElemType e)
- {
- // TODO (#1#): 在链表中插入元素
- int j;
- if(i<1||i>L.length+1) return ERROR;
- for(j=L.length;j>=i;j--)
- {
- L.elem[j]=L.elem[j-1];
- }
- L.elem[i-1]=e;
- ++L.length;
- return OK;
- //-------------------------------------
- }
删除表L中第i个元素,结果用e返回. 操作成功返回OK,失败时返回ERROR
- Status ListDelete(SqList &L, int i, ElemType &e)
- {
- // TODO (#1#): 在顺序表中删除元素
- int j;
- if(i<1||i>L.length) return ERROR;
- e=L.elem[i-1];
- for(j=i-1;j<L.length;j++)
- {
- L.elem[j]=L.elem[j+1];
- }
- --L.length;
- return OK;
- //-------------------------------------
- }
带有附件,需要可以下载