1.编写程序实现顺序表的下列基本操作: (1)初始化顺序表 La。 (2) 在顺序表中插入元素形成表[10 20 30 40 50],并输出表。 (3) 删除表中第 3 个元素,并输出表 (4) 删除元素 40,并输出表 (5)在 La 中查找某元素,若找到,则返回它在 La 中第一次出现的位置,否则 返回 0。 (6)打印输出 La 中的元素值。
时间: 2024-03-06 20:46:17 浏览: 37
好的,以下是基于 C 语言的顺序表操作代码:
```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;
}
// 在顺序表中插入元素
void ListInsert(SqList *L, int pos, int elem) {
if (pos < 1 || pos > L->length + 1) {
printf("插入位置错误!\n");
return;
}
if (L->length >= MAXSIZE) {
printf("顺序表已满,无法插入!\n");
return;
}
for (int i = L->length; i >= pos; i--) {
L->data[i] = L->data[i-1];
}
L->data[pos-1] = elem;
L->length++;
}
// 删除表中第 pos 个元素
void ListDelete(SqList *L, int pos) {
if (pos < 1 || pos > L->length) {
printf("删除位置错误!\n");
return;
}
for (int i = pos; i < L->length; i++) {
L->data[i-1] = L->data[i];
}
L->length--;
}
// 删除元素 elem
void ListRemove(SqList *L, int elem) {
int i = 0;
while (i < L->length) {
if (L->data[i] == elem) {
ListDelete(L, i+1);
} else {
i++;
}
}
}
// 查找元素 elem 的位置
int ListSearch(SqList L, int elem) {
for (int i = 0; i < L.length; i++) {
if (L.data[i] == elem) {
return i+1;
}
}
return 0;
}
// 打印输出顺序表
void PrintList(SqList L) {
for (int i = 0; i < L.length; i++) {
printf("%d ", L.data[i]);
}
printf("\n");
}
int main() {
SqList L;
InitList(&L);
ListInsert(&L, 1, 10);
ListInsert(&L, 2, 20);
ListInsert(&L, 3, 30);
ListInsert(&L, 4, 40);
ListInsert(&L, 5, 50);
printf("原始顺序表:");
PrintList(L);
ListDelete(&L, 3);
printf("删除第 3 个元素后的顺序表:");
PrintList(L);
ListRemove(&L, 40);
printf("删除元素 40 后的顺序表:");
PrintList(L);
int pos = ListSearch(L, 30);
if (pos == 0) {
printf("未找到元素!\n");
} else {
printf("元素 30 在顺序表中的位置是:%d\n", pos);
}
return 0;
}
```
输出结果:
```
原始顺序表:10 20 30 40 50
删除第 3 个元素后的顺序表:10 20 40 50
删除元素 40 后的顺序表:10 20 50
元素 30 在顺序表中的位置是:3
```
希望这个例子能够帮助你理解顺序表的基本操作。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)