试编写在单链表上实现插入和删除的算法(使用c语言)
时间: 2024-06-16 12:06:09 浏览: 11
在单链表上实现插入和删除的算法可以通过以下方式实现:
1. 插入算法:
- 首先,创建一个新节点,并将要插入的数据存储在该节点中。
- 然后,找到要插入位置的前一个节点,将新节点的next指针指向该节点的next指针。
- 最后,将前一个节点的next指针指向新节点,完成插入操作。
2. 删除算法:
- 首先,找到要删除节点的前一个节点。
- 然后,将前一个节点的next指针指向要删除节点的next指针,跳过要删除的节点。
- 最后,释放要删除节点的内存空间,完成删除操作。
下面是使用C语言实现插入和删除算法的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
struct Node {
int data;
struct Node* next;
};
// 在链表中插入节点
void insertNode(struct Node** head, int data) {
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
// 如果链表为空,则将新节点作为头节点
if (*head == NULL) {
*head = newNode;
return;
}
// 找到要插入位置的前一个节点
struct Node* prevNode = *head;
while (prevNode->next != NULL) {
prevNode = prevNode->next;
}
// 将新节点插入到链表中
prevNode->next = newNode;
}
// 在链表中删除节点
void deleteNode(struct Node** head, int data) {
// 如果链表为空,则直接返回
if (*head == NULL) {
return;
}
// 如果要删除的节点是头节点
if ((*head)->data == data) {
struct Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
// 找到要删除节点的前一个节点
struct Node* prevNode = *head;
while (prevNode->next != NULL && prevNode->next->data != data) {
prevNode = prevNode->next;
}
// 如果找到了要删除的节点
if (prevNode->next != NULL) {
struct Node* temp = prevNode->next;
prevNode->next = temp->next;
free(temp);
}
}
// 打印链表
void printList(struct Node* head) {
struct Node* currentNode = head;
while (currentNode != NULL) {
printf("%d ", currentNode->data);
currentNode = currentNode->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
// 插入节点
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
// 打印链表
printf("链表:");
printList(head);
// 删除节点
deleteNode(&head, 2);
// 打印链表
printf("删除节点后的链表:");
printList(head);
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)