記錄學習數據結構書籍<<大話數據結構>>的學習筆記。
線性表的順序存儲結構:用一段地址連續的存儲單元依次存儲線性表的數據元素
#include "stdio.h"
#define MAXSIZE 20
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef int ElemType;
/*對應結構體的定義*/
typedef struct
{
ElemType data[MAXSIZE];
int length;
}SqList;
/*獲取線性表中的第i個元素*/
/*用e返回L中的第i個元素的值*/
Status GetElem(SqList L,int i,ElemType *e)
{
if(L.length==0 || i<1 || i>L.length)
{
return ERROR;
}
*e=L.data[i-1];
return OK;
}
/*在L中第i個位置之前插入新的元素e,L的長度爲1*/
Status ListInsert(SqList *L,int i,ElemType e)
{
int k;
if (L->length==MAXSIZE) /*順序線性表已經滿*/
{
return ERROR;
}
if(i<1 || i>L->length+1) /*i不在範圍內*/
{
return ERROR;
}
if(i<=L->length) /*插入數據位置不在表尾部*/
{
for(k=L->length-1;k>=i-1;k--) /*將要插入位置後的數據元素向後移動一位*/
{
L->data[k+1]=L->data[k];
}
}
L->data[i-1]=e; /*將新元素插入*/
L->length++;
return OK;
}
/*刪除第i個數據元素,並用e返回其值,L的長度減1*/
Status ListDelete(SqList *L,int i,ElemType *e)
{
int k;
if(L->length==0) /*線性表爲空*/
{
return ERROR;
}
if(i<1||i>L->length) /*需要刪除的位置不對*/
{
return ERROR;
}
*e=L->data[i-1]; /*記錄需要刪除元素*/
if(i<L->length) /*需要刪除的元素不是最後一位*/
{
for(k=i;k<L->length;k++) /*後面的元素依次向前移動*/
{
L->data[k-1]=L->data[k];
}
}
L->length--;
return OK;
}
/*遍歷所有元素*/
void ListErgodic(SqList *L)
{
int len=0;
len = L->length;
for(len=0;len<=L->length-1;len++)
{
printf("第%d個元素是%d\r\n",len,L->data[len]);
}
}
/*測試案例*/
void main(void)
{
SqList Q;
int number;
ListInsert(&Q,1,23); //插入一個元素
ListInsert(&Q,1,22); //插入一個元素
ListInsert(&Q,2,21); //插入一個元素
ListErgodic(&Q); //遍歷所有元素
printf("當前的長度爲%d\r\n",Q.length);
ListDelete(&Q,2,&number); //刪除第2個元素
printf("當前的長度爲%d\r\n",Q.length);
printf("刪除的元素是%d\r\n",number);
}
運行測試輸出結果打印
線性表的順序存儲結構的優缺點:
優點:
1.可以快速存取表中任意位置的元素。
2.無需爲表示表中元素之間的邏輯關係而增加額外的存儲空間。
缺點:
1.插入和刪除元素時,需要進行大量的數據移動操作。
2.當線性表長度變化較大時,難以確定存儲空間的容量。