用C语言实现1、输入线性表长度,并依次输入线性表的每一项。2、展示线性表中的内容。3、输入在第i个位置插入元素,输入元素值。4、展示线性表中的内容。5、输入在第i个位置删除元素,输入元素值。6、展示线性表中的内容
时间: 2024-09-18 12:14:25 浏览: 38
在C语言中,我们可以使用结构体表示线性表,并结合指针来实现上述功能。这里是一个简单的示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义一个结构体表示线性表的节点
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建新节点并初始化
Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode != NULL) {
newNode->data = value;
newNode->next = NULL;
}
return newNode;
}
// 插入节点到链表
void insertNode(Node** head, int position, int value) {
if (position <= 0) {
printf("Invalid position.\n");
return;
}
Node* newNode = createNode(value);
if (*head == NULL) {
*head = newNode;
return;
}
Node* current = *head;
for (int i = 0; i < position - 1 && current != NULL; i++) {
current = current->next;
}
if (current == NULL) {
printf("Position out of range.\n");
return;
}
newNode->next = current->next;
current->next = newNode;
}
// 删除节点
void deleteNode(Node** head, int position, int valueToRemove) {
if (*head == NULL || position <= 0) {
printf("Invalid input.\n");
return;
}
Node* prev = NULL;
Node* current = *head;
for (int i = 0; i < position - 1 && current != NULL; i++) {
prev = current;
current = current->next;
}
if (current == NULL || current->data != valueToRemove) {
printf("Element not found or position invalid.\n");
return;
}
if (prev == NULL) { // 如果删除的是头结点
*head = current->next;
} else {
prev->next = current->next;
}
}
// 显示链表内容
void displayList(Node* head) {
if (head == NULL) {
printf("The list is empty.\n");
} else {
Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
}
int main() {
Node* head = NULL;
int length, position, value, index;
printf("Enter the length of the linear list: ");
scanf("%d", &length);
// 输入并显示原始线性表内容
for (int i = 0; i < length; i++) {
printf("Enter element at position %d: ", i + 1);
scanf("%d", &value);
insertNode(&head, i + 1, value);
displayList(head);
}
printf("Enter position to insert an element: ");
scanf("%d", &position);
printf("Enter value to insert: ");
scanf("%d", &value);
insertNode(&head, position, value);
displayList(head);
printf("Enter position to delete an element: ");
scanf("%d", &position);
printf("Enter value to delete: ");
scanf("%d", &valueToRemove);
deleteNode(&head, position, valueToRemove);
displayList(head);
return 0;
}
```
在这个示例中,我们首先创建一个链表,然后分别处理插入、删除和显示操作。注意这个程序假设用户提供的数据都是有效的,实际应用中需要添加错误检查和异常处理。
阅读全文