順序映象:以 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;
- //-------------------------------------
- }
帶有附件,需要可以下載