#include<iostream>
#include<string>
using namespace std;
#define LISTMAX 100
//测试结构
struct Person {
int age;
string name;
};
//创建静态链表初始结构
struct LinkList {
void* data;
int cur;
};
//初始化链表
LinkList* init_list(LinkList list[]){
for (int i = 0; i < LISTMAX; i++) {
list[i].cur = i+1;
}
list[LISTMAX-1].cur = 0;
return list;
}
//插入操作
void Insert_List(LinkList list[],int pos,void* data) {
if (list == NULL)
return;
if (list[LISTMAX - 1].cur == 0) {
list[LISTMAX - 1].cur = 1;
list[0].data = data;
list[1].cur = 0;
return;
}
if (pos > list[0].cur&&pos < 0) {
cout << "不在数据范围" << endl;
return;
}
//表数据后移
int b = list[0].cur;
for (int i = pos; i < list[0].cur; i++) {
list[b].data = list[b-1].data;
b--;
}
//恢复0值cur
list[list[0].cur -1].cur = list[0].cur;
//插入新数据
list[pos].data = data;
//重新为表确定0标记,确定可插入位置
list[list[0].cur].cur = 0;
//更新表长度标记
list[0].cur++;
}
//删除元素
void Delete_List(LinkList list[],int pos) {
if (list == NULL) {
cout << "list不存在" << endl;
return;
}
if (pos<0 || pos>list[0].cur - 1) {
cout << "删除元素不在范围" << endl;
return;
}
//前移覆盖删除节点数据
for (int i = pos; i < list[0].cur; i++) {
list[pos].data = list[pos+1].data;
}
//重新为0标记赋值
list[list[0].cur-1].cur = list[0].cur;
//更新表长度
list[0].cur--;
//确定新的0标记点
list[list[0].cur-1].cur = 0;
}
//遍历表元素
void foreach_list(LinkList list[]) {
if (list == NULL) {
cout << "空表或不存在"<<endl;
return;
}
for (int i = 0; i < list[0].cur; i++) {
Person* p = (Person*)list[i].data;
cout << "姓名: " << p->name << " " << "年龄:" << p->age<<" "<< list[i].cur<<endl;
}
}
void text() {
Person* Pa = new Person();
Person* Pb = new Person();
Person* Pc = new Person();
Person* Pd = new Person();
Pa->age = 20;
Pa->name = "李四1";
Pb->age = 21;
Pb->name = "李四2";
Pc->age = 22;
Pc->name = "李四3";
Pd->age = 23;
Pd->name = "李四4";
LinkList list[LISTMAX] ;
init_list(list);
Insert_List(list, 0, Pa);
Insert_List(list, 0, Pb);
Insert_List(list, 0, Pc);
Insert_List(list, 0, Pd);
Delete_List(list, 2);
foreach_list(list);
}
int main() {
text();
system("pause");
return 0;
}