静态链表
—— 头文件
#include <stdio.h>
#define maxSize 6
结构体声明静态链表节点
typedef struct {
int data;
int cur;
} component;
构建创建静态链表的函数(包括备用链表)
void reserveArr(component *array){
for (int i = 0; i < maxSize; i++) {
array[i].cur = i + 1;
array[i].data = -1;
}
array[maxSize-1].cur = 0;
}
int mallocArr(component *array){
int i = array[0].cur;
if (array[0].cur) {
array[0].cur = array[i].cur;
}
return i;
}
int initArr(component *array, int length){
reserveArr(array);
int body = 1;
int tempBody = body;
for (int i = 1; i < length + 1; i++) {
int j = mallocArr(array);
array[tempBody].cur = j+1;
array[tempBody].data = i;
tempBody = j+1;
}
array[tempBody-1].cur = 0;
return body;
}
构造展示静态链表元素的函数
void displayArr(component *array, int body){
int tempBody = body;
printf("静态链表为:");
while (array[tempBody].cur) {
printf("%d,%d ", array[tempBody].data, array[tempBody].cur);
tempBody = array[tempBody].cur;
}
printf("%d,%d\n", array[tempBody].data, array[tempBody].cur);
}
构造插入静态链表元素的函数
void insertArr(component *array, int body, int position, int elem){
int tempBody = body;
for(int i = 1; i < position - 1; i++){
tempBody = array[tempBody].cur;
}
int insert = mallocArr(array);
array[insert].data = elem;
array[insert].cur = array[tempBody].cur;
array[tempBody].cur = insert;
}
构造删除静态链表元素的函数
void freeArr(component * array, int k){
array[k].cur = array[0].cur;
array[0].cur = k;
}
void deletArr(component *array, int body, int elem){
int tempBody = body;
while (array[tempBody].data != elem) {
tempBody = array[tempBody].cur;
if (tempBody == 0) {
printf("链表中没有此数据");
return;
}
}
int del = tempBody;
tempBody = body;
while (array[tempBody].cur != del) {
tempBody = array[tempBody].cur;
}
array[tempBody].cur = array[del].cur;
freeArr(array, del);
}
构造查找静态链表元素的函数
int selectElem(component *array, int body, int elem){
int tempBody = body;
while(array[tempBody].cur != 0){
if(array[tempBody].data == elem){
return tempBody;
}
tempBody = array[tempBody].cur;
}
return -1;
}
构造更新静态链表元素的函数
void updateElem(component *array, int body, int oldelem, int newelem){
int position = selectElem(array, body, oldelem);
if(position == -1){
printf("无更改元素\n");
return;
}
array[position].data = newelem;
}
—— 主函数
int main() {
component array[maxSize];
int body = initArr(array, 3);
displayArr(array, body);
insertArr(array, 1, 3, 4);
displayArr(array, body);
deletArr(array, 1, 2);
displayArr(array, body);
printf("其索引下标为:%d\n", selectElem(array, 1, 4));
updateElem(array, 1, 4, 100);
displayArr(array, body);
return 0;
}