c语言初始化一个包含十个数字的简单顺序表,并对其实现插入,删除,查询操作
时间: 2024-05-08 15:15:03 浏览: 17
以下是C语言代码实现:
```c
#include <stdio.h>
#define MAX_SIZE 10
typedef struct {
int data[MAX_SIZE];
int length;
} SqList;
// 初始化顺序表
void initList(SqList *list) {
list->length = 0;
}
// 插入元素
int insert(SqList *list, int index, int value) {
if (list->length == MAX_SIZE) {
printf("List is full\n");
return 0;
}
if (index < 1 || index > list->length+1) {
printf("Invalid index\n");
return 0;
}
for (int i = list->length; i >= index; i--) {
list->data[i] = list->data[i-1];
}
list->data[index-1] = value;
list->length++;
return 1;
}
// 删除元素
int delete(SqList *list, int index) {
if (list->length == 0) {
printf("List is empty\n");
return 0;
}
if (index < 1 || index > list->length) {
printf("Invalid index\n");
return 0;
}
for (int i = index; i < list->length; i++) {
list->data[i-1] = list->data[i];
}
list->length--;
return 1;
}
// 查询元素
int search(SqList *list, int value) {
for (int i = 0; i < list->length; i++) {
if (list->data[i] == value) {
return i+1;
}
}
return 0;
}
int main() {
SqList list;
initList(&list);
// 初始化顺序表
for (int i = 0; i < MAX_SIZE; i++) {
list.data[i] = i+1;
list.length++;
}
// 插入元素
insert(&list, 3, 99);
printf("List after insert: ");
for (int i = 0; i < list.length; i++) {
printf("%d ", list.data[i]);
}
printf("\n");
// 删除元素
delete(&list, 5);
printf("List after delete: ");
for (int i = 0; i < list.length; i++) {
printf("%d ", list.data[i]);
}
printf("\n");
// 查询元素
int index = search(&list, 8);
if (index) {
printf("Value 8 found at index %d\n", index);
} else {
printf("Value 8 not found\n");
}
return 0;
}
```
输出结果:
```
List after insert: 1 2 99 3 4 5 6 7 8 9
List after delete: 1 2 99 3 5 6 7 8 9
Value 8 found at index 8
```
相关推荐
![](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)