You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
1.9 KiB

#include <stdlib.h>
#include <stdio.h>
//顺序存储的线性表
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int length;
} SeqList;
void initList(SeqList *L);
void insertList(SeqList *L, int index, int element);
//初始化线性表
void initList(SeqList *L) {
L->length = 0;
}
//线性表插入元素
void insertList(SeqList *L, int index, int element) {
//在顺序表 L 中第 index 之前,插入新元素 element
int j;
if (index < 1 || index > L->length + 1) {
printf("Invalid index!\n");
return;
}
if (L->length >= MAX_SIZE) {
printf("List overflow!\n");
return;
}
//依次后移法
for (j = L->length - 1; j >= index - 1; j--) {
L->data[j + 1] = L->data[j];
}
L->data[index - 1] = element;
L->length++;
}
//线性表删除元素
int deleteList(SeqList *L, int index) {
if (index < 0 || index >= L->length) {
printf("Invalid index!\n");
exit(0);
}
int x = L->data[index - 1];
for (int j = index; j <= L->length; j++) {
L->data[j - 1] = L->data[j];
}
L->length--;
return x;
}
//获取线性表的长度
int listLength(SeqList L) {
return L.length;
}
//获取某个位置的元素
int getElem(SeqList *L, int i) {
if (i < 1 || i > L->length) {
return 0;
}
return L->data[i - 1];
}
//获取元素的位置
int locateElem(SeqList *L, int e) {
for (int i = 0; i < L->length; i++) {
if (L->data[i] == e) {
return i + 1;
}
}
return 0;
}
//遍历线性表
void readList(SeqList *L) {
if (L->length > 0) {
printf("线性表的长度是%d\n{", L->length);
for (int i = 0; i < L->length - 1; i++) {
printf("%d,", L->data[i]);
}
printf("%d}", L->data[L->length - 1]);
} else {
printf("List is empty!");
}
}