(2)按如下要求编写主函数main 代码,测试顺序表的基本操作功能,执行程序并截图 运行结果。 void main(void)( int i=0: List L=NULL;/声明指向顺序表的指针变量 //创建一个空的顺序表 //初始化顺序表 //显示顺序表所有元素 W在位序为2的地方插入值10 //显示顺序表所有元素 //删除第3个元素 /显示顺序表所有元素 //查找值为x的元素位置并显示//查找值为x的元素位置并显示以上是你的代码
时间: 2023-05-25 13:04:12 浏览: 38
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
typedef struct {
int data[MAXSIZE];
int length;
} List;
List* createList() {
List* L;
L = (List*)malloc(sizeof(List));
L->length = 0;
return L;
}
void initList(List* L) {
int i;
for (i=0; i<MAXSIZE; i++) {
L->data[i] = 0;
}
L->length = 0;
}
void displayList(List* L) {
int i;
for (i=0; i<L->length; i++) {
printf("%d ", L->data[i]);
}
putchar('\n');
}
void insertList(List* L, int i, int value) {
int j;
if (i < 1 || i > L->length+1) {
printf("Position error!\n");
return;
}
if (L->length >= MAXSIZE) {
printf("List is full!\n");
return;
}
for (j=L->length-1; j>=i-1; j--) {
L->data[j+1] = L->data[j];
}
L->data[i-1] = value;
L->length++;
}
void deleteList(List* L, int i) {
int j;
if (i < 1 || i > L->length) {
printf("Position error!\n");
return;
}
for (j=i; j<L->length; j++) {
L->data[j-1] = L->data[j];
}
L->length--;
}
int searchList(List* L, int value) {
int i;
for (i=0; i<L->length; i++) {
if (L->data[i] == value) {
return i+1;
}
}
return -1;
}
int main() {
List* L;
int i, x, pos;
// 创建一个空的顺序表
L = createList();
// 初始化顺序表
initList(L);
// 显示顺序表所有元素
displayList(L);
// 在位序为2的地方插入值10
insertList(L, 2, 10);
// 显示顺序表所有元素
displayList(L);
// 删除第3个元素
deleteList(L, 3);
// 显示顺序表所有元素
displayList(L);
// 查找值为x的元素位置并显示
printf("Please enter a value: ");
scanf("%d", &x);
pos = searchList(L, x);
if (pos != -1) {
printf("The position of %d is %d\n", x, pos);
} else {
printf("The value %d is not found\n", x);
}
return 0;
}