静态分配代码:
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
typedef struct LinkList
{int data[MAX];int lenth;
}Link;
//初始化
void CreateList(Link* L)
{L->lenth = 0;for (int i = 0; i < MAX; i++){L->data[i] = 0;}
}
//插入
int LinkInsert(Link* L,int i,int e)
{if (i<1 || i>L->lenth + 1){printf("需要插入的位序错误\n");return 0;}if (L->lenth > MAX){printf("顺序表已满,不能进行插入操作\n");return 0;}for (int j=L->lenth; j >=i ; j--){L->data[j] = L->data[j-1];}L->data[i - 1] = e;L->lenth++;return 1;
}
//删除
int ListDesert(Link* L, int i)
{if (i<1 || i>MAX){printf("需要删除的位序错误\n");return 0;}int e = L->data[i - 1];for (int j = i; j < L->lenth; j++){L->data[j - 1] = L->data[j];}L->lenth--;return e;
}
//输出
void Print(Link* L)
{printf("顺序表为:");for (int i = 0; i < L->lenth; i++){printf("%d ",L->data[i]);}printf("\n");
}
//按值查找
int LocateElem(Link* L, int e)
{for (int i = 0; i < L->lenth; i++){if (e == L->data[i]){return i + 1;}}return 0;
}
//按位查找
int GetElem(Link* L, int o)
{return L->data[o-1];
}
int main()
{//初始化Link* L;L = (Link*)malloc(sizeof(Link));CreateList(L);//插入int i, e;while (1){printf("请输入需要插入的位置i,和需要插入的值e,i为99999时结束插入\n");scanf("%d %d", &i, &e);LinkInsert(L, i, e);if (i == 99999){printf("插入结束\n");break;}Print(L);}//删除int j;while (1){printf("请输入需要删除的位置j,j为99999是结束删除\n");scanf("%d", &j);ListDesert(L, j);if (j == 99999 || L->lenth == 0){printf("结束删除操作\n");break;}Print(L);}//按值查找int k;printf("请输入需要查找的值\n");scanf("%d",&k);int g=LocateElem(L, k);printf("需要查找的值在第%d位\n",g);//按位查找int o;printf("请输入需要查找的位序\n");scanf("%d",&o);int m=GetElem(L, o);printf("第%d的数据为%d\n",o,m);return 0;
}