C语言编写顺序表的代码
时间: 2023-04-10 17:00:23 浏览: 102
C语言实现顺序表代码.rar
5星 · 资源好评率100%
以下是C语言编写顺序表的代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int length;
} SqList;
void InitList(SqList *L) {
L->length = 0;
}
int ListInsert(SqList *L, int i, int e) {
if (i < 1 || i > L->length + 1 || L->length == MAXSIZE) {
return 0;
}
for (int j = L->length; j >= i; j--) {
L->data[j] = L->data[j - 1];
}
L->data[i - 1] = e;
L->length++;
return 1;
}
int ListDelete(SqList *L, int i) {
if (i < 1 || i > L->length) {
return 0;
}
for (int j = i; j < L->length; j++) {
L->data[j - 1] = L->data[j];
}
L->length--;
return 1;
}
int GetElem(SqList L, int i) {
if (i < 1 || i > L.length) {
return -1;
}
return L.data[i - 1];
}
int LocateElem(SqList L, int e) {
for (int i = 0; i < L.length; i++) {
if (L.data[i] == e) {
return i + 1;
}
}
return 0;
}
int main() {
SqList L;
InitList(&L);
ListInsert(&L, 1, 1);
ListInsert(&L, 2, 2);
ListInsert(&L, 3, 3);
printf("%d\n", GetElem(L, 2));
printf("%d\n", LocateElem(L, 3));
ListDelete(&L, 2);
printf("%d\n", GetElem(L, 2));
return 0;
}
```
阅读全文