编写在单链表上实现插入和删除的算法使用c语言
时间: 2024-06-16 11:06:10 浏览: 13
在C语言中,可以使用结构体和指针来实现单链表,并编写插入和删除的算法。下面是一个简单的示例:
首先,定义一个表示链表节点的结构体:
```c
typedef struct Node {
int data; // 节点数据
struct Node* next; // 指向下一个节点的指针
} Node;
```
接下来,定义插入节点的函数:
```c
void insertNode(Node** head, int data) {
Node* newNode = (Node*)malloc(sizeof(Node)); // 创建新节点
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode; // 如果链表为空,将新节点设为头节点
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next; // 找到链表的最后一个节点
}
current->next = newNode; // 将新节点插入到最后一个节点的后面
}
}
```
然后,定义删除节点的函数:
```c
void deleteNode(Node** head, int data) {
if (*head == NULL) {
return; // 如果链表为空,直接返回
}
Node* current = *head;
Node* prev = NULL;
// 遍历链表,找到要删除的节点
while (current != NULL && current->data != data) {
prev = current;
current = current->next;
}
if (current == NULL) {
return; // 如果没有找到要删除的节点,直接返回
}
if (prev == NULL) {
*head = current->next; // 如果要删除的节点是头节点,更新头指针
} else {
prev->next = current->next; // 将要删除的节点从链表中移除
}
free(current); // 释放内存
}
```
使用以上定义的函数,可以进行单链表的插入和删除操作。以下是示例代码:
```c
int main() {
Node* head = NULL;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
deleteNode(&head, 2);
// 输出链表中的数据
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
return 0;
}
```
输出结果为:1 3
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)