Github:(https://github.com/FlameCharmander/DataStructure)
線性表分爲順序表和鏈表。
以下是順序表的實現,爲了簡單,沒用考慮健壯性(沒有對i的合法性進行判斷等。)
#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
#define INCREMENT 50
typedef int BOOL;
#define TRUE 1
#define FALSE 0
typedef char ElemType;
typedef struct{
ElemType data[SIZE]; //元素數組
int length; //長度
int capacity; //容量
}SqList;
void InitList(SqList* list); //初始化順序表
BOOL Insert(SqList* list, ElemType e, int i); //插入
BOOL Delete(SqList* list, ElemType e); //刪除
BOOL IsEmpty(SqList* list); //判斷爲空
int main()
{
SqList list;
InitList(&list);
printf("%d\n", IsEmpty(&list));
Insert(&list, 'a', 1);
printf("%d\n", IsEmpty(&list));
Delete(&list, 'b');
printf("%d\n", IsEmpty(&list));
Delete(&list, 'a');
printf("%d\n", IsEmpty(&list));
return 0;
}
void InitList(SqList* list){
list->length = 0;
list->capacity = SIZE;
}
BOOL Insert(SqList* list, ElemType e, int pos){ //pos的範圍1<=pos<=n
int i;
++list->length;
for (i = list->length; i > pos-1; --i){
list->data[list->length] = list->data[list->length-1];
}
list->data[pos-1] = e;
return TRUE;
}
BOOL Delete(SqList* list, ElemType e){
int i, j;
for (i = 0; i < list->length; ++i){
if (list->data[i] == e){ //找到該元素
for (j = i; j < list->length; ++j){
list->data[j] = list->data[j+1];
--list->length;
return TRUE;
}
}
}
return FALSE;
}
BOOL IsEmpty(SqList* list){
if (list->length == 0) {
return TRUE;
} else {
return FALSE;
}
}
這裏我建議你打開兩個窗口來講下面的解釋和代碼一一對應來看。
Line 1~2 導入頭文件
Line 4~5 數組的大小,以及增長的長度(這裏我並沒有用到,因爲爲了考慮健壯性)
Line 12~16 順序表的數據結構,一個是元素數組,存放元素的,一個是順序表的大小,一個是容量(數組有容量的大小,比如我們這裏就分配了100個,超過了就會溢出,這時的解決辦法就是重新分配一塊更大的數組,這也就是上面增長長度的作用)。
Line 18~21 真實的一些操作遠不止這些,說過了,這是簡單實現,太多的代碼很容易擊退自信心,然後有註釋,可以看一下
Line 23~35 主要是在main函數裏,對錶的操作進行測試
Line 37~39 爲順序表進行初始化,剛開始數組大小爲0,然後容量是100
Line 42~50 這裏注意,因爲C語言裏(包括很多別的類C語言)數組是從0開始的,而我們爲了通用性,不考慮這些實現,所以那個pos的大小爲1<=pos<=n,當把元素插入其中的位置時,我們需要後移元素(你們可以畫個數組,比如現在有個順序表是1 3 4 5 6,你們要元素10插入到2的位置時,先要把3 4 5 6後移,變成1 3 3 4 5 6,然後把第二個3換成10,最終形成1 10 3 4 5 6)。
Line 44 先把順序表長度增加1位
Line 45~47 元素後移
Line 48 把插入的元素寫到當前的位置,爲什麼是pos-1,說過了,數組是從0開始的,我們要插入第2個位置就是數組裏面下標爲1的那個位置。
Line 52~64 要刪除順序表的一個元素。思路就是先走到那個元素,還是剛纔那個表(1 10 3 4 5 6),比如要刪除3,只要找到3的位置,然後把4 5 6向前移動,變成(1 10 4 5 6 6 ),還有個6在數組怎麼辦,我們邏輯刪除它,就是把順序表的長度減少一位就可以了。
Line 54 循環,找到要刪除的元素
Line 55 如果相等,說明找到了
Line 56~59 把元素向前移動,並且--list->length;
,把長度減少。並且返回真
Line 63 如果沒找到要刪除的元素,會執行這句代碼,返回假
Line 66~72 判斷順序表的大小是否爲0就知道是否爲空。