试编写在单链表上实现插入和删除的算法。用c语言插入元素自主输入
时间: 2024-06-16 14:06:16 浏览: 14
在单链表上实现插入和删除元素的算法可以通过以下步骤进行:
1. 插入元素:
- 创建一个新节点,并为其分配内存空间。
- 将要插入的元素赋值给新节点的数据域。
- 将新节点的指针域指向原链表中要插入位置的下一个节点。
- 将原链表中要插入位置的前一个节点的指针域指向新节点。
2. 删除元素:
- 找到要删除的节点的前一个节点。
- 将前一个节点的指针域指向要删除节点的下一个节点。
- 释放要删除节点的内存空间。
下面是一个用C语言实现单链表插入和删除元素的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
struct Node {
int data;
struct Node* next;
};
// 在链表中插入元素
void insert(struct Node** head, int value) {
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
// 如果链表为空,直接将新节点作为头节点
if (*head == NULL) {
*head = newNode;
return;
}
// 找到链表尾部节点
struct Node* tail = *head;
while (tail->next != NULL) {
tail = tail->next;
}
// 将新节点插入到链表尾部
tail->next = newNode;
}
// 在链表中删除元素
void remove(struct Node** head, int value) {
// 如果链表为空,直接返回
if (*head == NULL) {
return;
}
// 如果要删除的节点是头节点
if ((*head)->data == value) {
struct Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
// 找到要删除节点的前一个节点
struct Node* prev = *head;
while (prev->next != NULL && prev->next->data != value) {
prev = prev->next;
}
// 如果找到了要删除的节点
if (prev->next != NULL) {
struct Node* temp = prev->next;
prev->next = temp->next;
free(temp);
}
}
// 打印链表元素
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
// 插入元素
int value;
printf("请输入要插入的元素(输入-1结束):");
while (scanf("%d", &value) && value != -1) {
insert(&head, value);
printf("请输入要插入的元素(输入-1结束):");
}
// 打印链表
printf("链表元素:");
printList(head);
// 删除元素
printf("请输入要删除的元素:");
scanf("%d", &value);
remove(&head, value);
// 打印链表
printf("删除后的链表元素:");
printList(head);
return 0;
}
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)