c语言代码,输入整数n建立n个整数顺序表,功能有按值查找和删除元素,以及删除元素过后重新输出
时间: 2023-05-22 09:02:35 浏览: 142
好的,以下是c语言代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int* data;
int length;
} List;
void initList(List* list, int length) {
list->data = (int*)malloc(length * sizeof(int));
list->length = length;
}
void insertList(List* list, int index, int element) {
if (index < 0 || index >= list->length) {
printf("非法输入!\n");
return;
}
list->data[index] = element;
}
int findIndex(List* list, int value) {
for (int i = 0; i < list->length; i++) {
if (list->data[i] == value) {
return i;
}
}
return -1;
}
void deleteIndex(List* list, int index) {
if (index < 0 || index >= list->length) {
printf("非法输入!\n");
return;
}
for (int i = index; i < list->length - 1; i++) {
list->data[i] = list->data[i + 1];
}
list->length--;
}
void printList(List* list) {
for (int i = 0; i < list->length; i++) {
printf("%d ", list->data[i]);
}
printf("\n");
}
int main() {
int n;
printf("请输入顺序表的长度: ");
scanf("%d", &n);
List list;
initList(&list, n);
printf("请输入%d个整数: ", n);
for (int i = 0; i < n; i++) {
int temp;
scanf("%d", &temp);
insertList(&list, i, temp);
}
printf("请输入要查找的值: ");
int value;
scanf("%d", &value);
int index = findIndex(&list, value);
if (index == -1) {
printf("未找到该值!\n");
} else {
printf("该值的索引为%d\n", index);
}
printf("请输入要删除的值: ");
int del;
scanf("%d", &del);
index = findIndex(&list, del);
if (index == -1) {
printf("未找到要删除的值\n");
} else {
deleteIndex(&list, index);
printf("删除成功,当前顺序表为: ");
printList(&list);
}
return 0;
}
请注意,为了保证程序的正确性,这里并没有进行完整的输入检测和异常处理,运行请自行注意。
阅读全文