DS之順序表,ds順序
順序表定義
線性表的順序表示指的是用一組地址連續的儲存單元依次儲存線性表的資料元素。線性表的順序儲存結構或順序映像通常被叫做順序表。順序表的特點為:以元素在電腦內“物理位置相鄰”來表示線性表中資料元素之間的邏輯關係。每一個資料元素的儲存位置都和線性表的起始位置相差一個和資料元素線上性表中的位序成正比的常數。因此,只要確定了儲存線性表的起始位置,線性表中任一資料元素都可以隨機存取,所以線性表的順序儲存結構是一種隨機存取的儲存結構。下面的圖很好的顯示了這種結構。
順序表的資料元素的插入與刪除的結構圖:
順序表的儲存結構代碼:
<span style="font-size:18px;">#define LIST_INIT_SIZE 100 #define LISTINCREMENT 10typedef int ElemType;typedef struct{ElemType *elem;//儲存空間基址int length;//當前長度int listsize;//當前分配的儲存容量}SqList;//定義了一個結構體類型,並命名為</span>
順序表的基本操作
0基本操作前的準備
<span style="font-size:18px;">#include <iostream>using namespace std;#include <malloc.h>#include <stdlib.h>#define TRUE 1#define FALSE 0#define OK 1#define ERROR 0#define OVERFLOW -2#define LIST_INIT_SIZE 100 #define LISTINCREMENT 10typedef int ElemType;typedef int Status;typedef struct{ElemType *elem;//儲存空間基址int length;//當前長度int listsize;//當前分配的儲存容量}SqList;//定義了一個結構體類型,並命名為</span>
1構建一個空的順序表
<span style="font-size:18px;">//1初始化順序表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; }</span>
2判斷順序表是否為空白
<span style="font-size:18px;">//2判斷順序表是否為空白Status ListEmpty(SqList L){return L.length==0;}</span>
3求順序表的長度
<span style="font-size:18px;">//3求順序表的長度Status ListLength(SqList L){return L.length;}</span>
4銷毀順序表
<span style="font-size:18px;">//4銷毀順序表Status DestroyList(SqList &L){if(L.elem){free(L.elem);}L.elem=NULL;return OK;}</span>
5清空順序表
<span style="font-size:18px;">Status ClearList(SqList &L){L.length=0;return OK;}</span>
6向順序表插入資料元素
<span style="font-size:18px;">Status ListInsert(SqList &L,int i, ElemType e){if(i<1||i>L.length+1){return ERROR;}if (L.length>=L.listsize){ElemType *newbase=(ElemType *)realloc(L.elem,(L.listsize+LISTINCREMENT )*sizeof(ElemType)); if(!newbase){exit(OVERFLOW);} L.elem=newbase; L.listsize+=LISTINCREMENT;} ElemType *q=&(L.elem[i-1]); ElemType *p; for(p=&(L.elem[L.length-1]);p>=q;p--) { *(p+1)=*p; } *q=e; ++L.length; return OK;</span><span style="font-size:18px;">}</span>
7返回順序表中的第i個元素
<span style="font-size:18px;">//7返回順序表中的第i個元素Status GetElem(SqList L,int i,ElemType &e){if(i<1||i>L.length){return ERROR;}e=L.elem[i-1];return OK;}</span>
8刪除順序表的第i個資料元素
<span style="font-size:18px;">//8刪除順序表的第i個資料元素Status ListDelete(SqList &L,int i,ElemType &e){if(i<1||i>L.length){return ERROR;}e=L.elem[i-1];for(i=0;i<L.length;i++){L.elem[i-1]=L.elem[i];--L.length;}return OK;}</span>