C语言编写,测试数据占两行,第一行为线性表LA的元素,元素间以空格隔开,元素数量不超过100个。第二行为需要删除的下标I,输出删除指定下标I后的顺序表
时间: 2024-09-12 10:16:24 浏览: 47
在C语言中,你可以通过动态内存分配和结构体来实现这个功能。首先,定义一个结构体来表示线性表的元素:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义线性表元素结构体
typedef struct {
int data;
} ListElement;
// 线性表的函数声明
ListElement* create_list(int* arr, int size);
void delete_element(ListElement** list, int index);
```
接下来,你可以编写`create_list` 函数来初始化线性表,并处理输入的数据:
```c
ListElement* create_list(int* arr, int size) {
ListElement* LA = (ListElement*)malloc(sizeof(ListElement) * size);
for (int i = 0; i < size; i++) {
LA[i].data = arr[i];
}
return LA;
}
```
删除指定下标的函数 `delete_element`:
```c
void delete_element(ListElement** list, int index) {
if (*list == NULL || index < 0 || index >= get_size(*list)) {
printf("Invalid input.\n");
return;
}
// Shift elements after the deleted index to fill the gap
for (int i = index; i < get_size(*list) - 1; i++) {
(*list)[i].data = (*list)[i + 1].data;
}
// Reduce the allocated memory by one
(*list)[get_size(*list) - 1].data = '\0'; // Mark end as null
free(&(*list)[index]); // Free the deleted element's memory
(*list)[get_size(*list) - 1] = NULL; // Update the last element pointer
}
// 获取线性表元素的数量
int get_size(ListElement* list) {
return list != NULL ? list->data : 0;
}
```
最后,用户输入和处理删除操作的例子:
```c
int main() {
int LA_input[100], delete_index;
printf("Enter elements of linear list LA separated by spaces:\n");
scanf("%d", &LA_input[0]);
for (int i = 1; i < 100 && scanf("%d", &LA_input[i]) == 1; i++) {} // Read until space or EOF
ListElement* LA = create_list(LA_input, i); // Create the list
printf("Enter the index of the element you want to delete: ");
scanf("%d", &delete_index);
delete_element(&LA, delete_index - 1); // Subtract 1 since indexing starts from 0
// Print the modified list
for (int i = 0; LA[i].data != '\0'; i++) {
printf("%d ", LA[i].data);
}
printf("\n");
free(LA); // Don't forget to deallocate memory when done
return 0;
}
```
运行这个程序,它会提示用户输入线性表的元素和要删除的下标,然后按照描述删除并输出修改后的列表。
阅读全文