用C语言编写程序:通过键盘读取元素建立一个单链表;指定一个元素,在此元素之前插入一个新元素;指定一个元素,删除此元素
时间: 2024-10-22 08:05:39 浏览: 21
C语言程序设计-输入一维数组的8个元素,并将最大值与最后一个数交换
5星 · 资源好评率100%
在C语言中,我们可以使用`stdio.h`库来进行键盘输入,`malloc`函数进行动态内存分配,以及定义链表节点结构来实现所需的功能。首先,让我们定义一个简单的链表节点结构:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建链表
Node* createList() {
Node* head = NULL;
int input;
printf("请输入元素,按回车结束:");
while (scanf("%d", &input) == 1) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = input;
newNode->next = head;
head = newNode;
}
return head;
}
// 在指定元素之前插入新元素
void insertBefore(Node** head, int targetValue, int newValue) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = newValue;
if (*head == NULL) {
newNode->next = *head;
*head = newNode;
return;
}
Node* current = *head;
while (current->data != targetValue && current->next != NULL) {
current = current->next;
}
if (current->next == NULL) {
newNode->next = *head;
*head = newNode;
} else {
newNode->next = current->next;
current->next = newNode;
}
}
// 删除指定元素
void deleteElement(Node** head, int targetValue) {
if (*head == NULL) return;
if ((*head)->data == targetValue) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* current = *head;
Node* previous = NULL;
while (current != NULL && current->data != targetValue) {
previous = current;
current = current->next;
}
if (current != NULL) {
previous->next = current->next;
free(current);
}
}
int main() {
Node* list = createList();
if (list == NULL) {
printf("无法创建链表.\n");
return 1;
}
printf("\n当前链表: ");
Node* temp = list;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
int target = 0; // 假设你想在这个元素之前插入或删除
int newValue = 5; // 新插入的值
printf("要在哪个元素前插入新值?\n");
scanf("%d", &target);
insertBefore(&list, target, newValue);
printf("插入新元素后的链表: ");
temp = list;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
printf("要删除哪个元素?\n");
scanf("%d", &target);
deleteElement(&list, target);
printf("删除元素后的链表: ");
temp = list;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
return 0;
}
```
这个程序会提示用户输入一系列数字,然后允许他们在指定元素前插入新元素和删除指定元素。请注意,输入的`target`值需与已经存在的元素匹配才能成功操作。
阅读全文