线性表的顺序表示
线性表的顺序表示,是通过构造一个结构体实现的。结构体内包含一个定长数组和一个顺序表的长度。一维数组可以是静态分配或者是动态分配的。这里使用的是静态分配的方法。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef int Position;
typedef struct LNode *List;
#define MAXSIZE 100
struct LNode{
int Data[MAXSIZE];
Position last;
};
List InitialList(){
List L;
L = (List) malloc(sizeof(List));
L->last = -1;
return L;
}
bool judgeEmpty(List L){
if (L->last == -1) return true;
else return false;
}
bool insert(List L, int element, int position){
if (position < 0){
printf("Error:插入的位置小于0\n");
return false;
}
if (position >= MAXSIZE){
printf("Error: 插入的位置超出最大长度\n");
return false;
}
if (L->last >= MAXSIZE - 1){
printf("Error:表已经满了,无法继续插入.\n");
}
for (int i = L->last; i >= position; i--){
L->Data[i + 1] = L->Data[i];
}
L->Data[position] = element;
L->last++;
return true;
}
Position find(List L, int element){
int i = 0;
while(L->Data[i] != element && i <= L->last)
i++;
if (i == L->last) return -1;
else return i;
}
bool deleteByIndex(List L, int index){
if (L->last == -1){
printf("The list is empty!\n");
return false;
}
if (index < 0 || index > L->last){
printf("Index is valid\n");
return false;
}
for(int i = index; i < L->last + 1; i++){
L->Data[i] = L->Data[i+1];
}
L->last--;
return true;
}
bool deleteByElement(List L