在正式介紹順序表之前,我們有必要先了解一個(gè)名詞:線性表。
線性表:
線性表是,具有n個(gè)相同特性的數(shù)據(jù)元素的有限序列。常見的線性表:順序表、鏈表、棧、隊(duì)列、數(shù)組、字符串...
線性表在邏輯上是線性結(jié)構(gòu),但在物理結(jié)構(gòu)上并不一定是連續(xù)的。
1. 順序表概念
順序表是用一段物理地址連續(xù)的儲存單元、依次存儲數(shù)據(jù)元素的線性結(jié)構(gòu),一般情況下采用數(shù)組存儲。
2. 順序表定義
typedef int SLDataType;// 順序表數(shù)據(jù)類型
typedef struct SeqList
{
SLDataType* arr; // 指向動態(tài)開辟的數(shù)組
int size; // 有效數(shù)據(jù)個(gè)數(shù)
int capacity; // 容量
}SL;
3. 順序表的初始化
順序表的初始化,是使用 動態(tài)內(nèi)存管理 開辟空間構(gòu)造一個(gè)空的順序表
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define DefaultCapacity 4 // 默認(rèn)初始化空間大小
void SLInit(SL* ps)
{
assert(ps);
SLDataType* tmp = (SLDataType*)malloc(sizeof(SLDataType) * DefaultCapacity);
if (tmp == NULL)
{
perror("malloc");
exit(-1);
}
ps->arr = tmp;
ps->capacity = DefaultCapacity;
ps->size = 0;
}
4. 在pos位置插入元素
在pos位置插入數(shù)據(jù)之前,要檢查動態(tài)順序表的容量是否足夠 ,
不夠則利用 realloc函數(shù) 開辟一塊更大的空間給順序表。
檢查容量/擴(kuò)容:
void SLCapacityCheck(SL* ps)
{
assert(ps);
if (ps->size == ps->capacity)
{
SLDataType* tmp = (SLDataType*)realloc(ps->arr, ps->capacity * 2 * sizeof(SLDataType));
if (tmp == NULL)
{
perror("realloc");
exit(-1);
}
ps->capacity *= 2;
ps->arr = tmp;
}
}
插入:
void SLInsert(SL* ps, int pos, SLDataType x)
{
assert(ps);
SLCapacityCheck(ps);
for (int i = ps->size - 1; i >= pos; i--)
{
ps->arr[i + 1] = ps->arr[i];
}
ps->arr[pos] = x;
ps->size++;
}
5. 刪除pos位置元素
void SLErase(SL* ps, int pos)
{
assert(ps);
for (int i = pos + 1; i < ps->size; i++)
{
ps->arr[i - 1] = ps->arr[i];
}
ps->size--;
}
6. 順序表查找(按值查找)
int SLFind(SL* ps, SLDataType x)
{
assert(ps);
for (int i = 0; i < ps->size; i++)
{
if (ps->arr[i] == x)
return i;
}
// 找不到所查找的元素
return -1;
}
在主函數(shù)中使用 SLFind函數(shù) 時(shí),應(yīng)檢驗(yàn) “返回值” 是否為非 -1,再使用文章來源:http://www.zghlxwxcb.cn/news/detail-643146.html
7. 順序表的打印
void SLPrint(SL* ps)
{
assert(ps);
for (int i = 0; i < ps->size; i++)
{
printf("%d ", ps->arr[i]);
}
printf("\n");
}
8. 順序表銷毀
void SLDestroy(SL* ps)
{
assert(ps);
free(ps->arr);
ps->capacity = 0;
ps->size = 0;
}
銷毀 arr 所指向的空間,將空間還給操作系統(tǒng)。文章來源地址http://www.zghlxwxcb.cn/news/detail-643146.html
到了這里,關(guān)于數(shù)據(jù)結(jié)構(gòu)(一):順序表詳解的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!