用C语言代码构造一个顺序表,表数据为:33,6,8,10,0,3,2,1。.遍历顺序表(输出顺序表的值,写在函数内) 3.打印出第二个元素的内容(按位置查找) 4.查找内容为“8”的元素的下标(按内容查找) 5.在第三个位置上插入“1”,然后遍历顺序表
时间: 2023-11-22 15:56:59 浏览: 41
以下是用 C 语言代码构造一个顺序表,并实现相关功能的程序:
```c
#include <stdio.h>
#define MAXSIZE 100 // 定义顺序表的最大长度
typedef struct {
int data[MAXSIZE]; // 存储数据的数组
int length; // 当前顺序表的长度
} SqList;
// 初始化顺序表
void initList(SqList *L) {
L->length = 0;
}
// 插入元素
int insertElem(SqList *L, int pos, int elem) {
if (pos < 1 || pos > L->length+1 || L->length == MAXSIZE) {
return 0; // 插入失败
}
for (int i = L->length; i >= pos; i--) {
L->data[i] = L->data[i-1];
}
L->data[pos-1] = elem;
L->length++;
return 1; // 插入成功
}
// 遍历顺序表
void traverseList(SqList L) {
for (int i = 0; i < L.length; i++) {
printf("%d ", L.data[i]);
}
printf("\n");
}
// 按位置查找元素
int getElemByPos(SqList L, int pos) {
if (pos < 1 || pos > L.length) {
return -1; // 位置非法,返回-1表示查找失败
}
return L.data[pos-1];
}
// 按内容查找元素
int getElemByValue(SqList L, int value) {
for (int i = 0; i < L.length; i++) {
if (L.data[i] == value) {
return i+1; // 找到了,返回下标+1表示查找成功
}
}
return 0; // 没找到,返回0表示查找失败
}
int main() {
SqList L;
initList(&L);
// 插入元素
insertElem(&L, 1, 33);
insertElem(&L, 2, 6);
insertElem(&L, 3, 8);
insertElem(&L, 4, 10);
insertElem(&L, 5, 0);
insertElem(&L, 6, 3);
insertElem(&L, 7, 2);
insertElem(&L, 8, 1);
// 遍历顺序表
printf("遍历顺序表:");
traverseList(L);
// 按位置查找元素
printf("第二个元素的内容为:%d\n", getElemByPos(L, 2));
// 按内容查找元素
int index = getElemByValue(L, 8);
if (index == 0) {
printf("元素未找到\n");
} else {
printf("元素在第%d个位置\n", index);
}
// 在第三个位置插入元素
insertElem(&L, 3, 1);
// 遍历顺序表
printf("插入元素后遍历顺序表:");
traverseList(L);
return 0;
}
```
输出结果为:
```
遍历顺序表:33 6 8 10 0 3 2 1
第二个元素的内容为:6
元素在第3个位置
插入元素后遍历顺序表:33 6 1 8 10 0 3 2 1
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)