单链表的插入和删除操作代码及运行结果
时间: 2024-02-17 07:04:47 浏览: 25
好的,以下是单链表的插入和删除操作的代码和运行结果。
```
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data; // 数据域
struct Node* next; // 指针域
} Node;
// 定义链表头结点
Node* head = NULL;
// 插入节点函数
void insertNode(int data) {
// 创建新节点
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
// 如果链表为空,则新节点为头结点
if (head == NULL) {
head = newNode;
return;
}
// 遍历链表,找到尾节点
Node* tail = head;
while (tail->next != NULL) {
tail = tail->next;
}
// 将新节点插入链表尾部
tail->next = newNode;
}
// 删除节点函数
void deleteNode(int data) {
// 如果链表为空,则直接返回
if (head == NULL) {
return;
}
// 如果要删除的是头结点,则直接删除
if (head->data == data) {
Node* temp = head;
head = head->next;
free(temp);
return;
}
// 遍历链表,找到要删除的节点
Node* current = head;
while (current->next != NULL && current->next->data != data) {
current = current->next;
}
// 如果找到了要删除的节点,则删除
if (current->next != NULL) {
Node* temp = current->next;
current->next = temp->next;
free(temp);
return;
}
}
// 打印链表函数
void printList() {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
// 插入节点
insertNode(1);
insertNode(2);
insertNode(3);
insertNode(4);
insertNode(5);
// 打印链表
printf("初始链表:");
printList();
// 删除节点
deleteNode(3);
// 打印链表
printf("删除节点3后的链表:");
printList();
return 0;
}
```
运行结果如下:
```
初始链表:1 2 3 4 5
删除节点3后的链表:1 2 4 5
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)