微信公众号:魔七宝
求关注!后续会将所有内容分享在公众号!!希望大家可以关注一下!!!谢谢!!!!
代码说明:
Node 结构体定义了单链表的节点,包含数据和指向下一个节点的指针。
createNode 函数用于创建新节点。
insertAtHead 和 insertAtTail 函数分别在链表头部和尾部插入节点。
deleteNode 函数用于删除链表中指定值的节点。
printList 函数用于遍历链表并打印节点数据。
main 函数中展示了如何使用上述函数来操作链表。
#include <stdio.h>
#include <stdlib.h>// 定义单链表节点结构体
typedef struct Node {
int data; // 节点数据
struct Node* next; // 指向下一个节点的指针
} Node;// 创建新节点的函数
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node)); // 分配内存
newNode->data = data; // 设置节点数据
newNode->next = NULL; // 初始化下一个指针为NULL
return newNode; // 返回新节点
}// 在链表头部插入节点的函数
void insertAtHead(Node** head, int data) {
Node* newNode = createNode(data); // 创建新节点
newNode->next = *head; // 新节点指向当前头节点
*head = newNode; // 更新头指针为新节点
}// 在链表尾部插入节点的函数
void insertAtTail(Node** head, int data) {
Node* newNode = createNode(data); // 创建新节点
if (*head == NULL) { // 如果链表为空
*head = newNode; // 直接将新节点设为头节点
return;
}
Node* temp = *head; // 临时指针指向头节点
while (temp->next != NULL) { // 遍历到链表尾部
temp = temp->next; // 移动到下一个节点
}
temp->next = newNode; // 将尾节点的next指向新节点
}// 删除链表中指定值的节点的函数
void deleteNode(Node** head, int key) {
Node* temp = *head; // 临时指针指向头节点
Node* prev = NULL; // 前驱指针初始化为NULL// 如果头节点是要删除的节点
if (temp != NULL && temp->data == key) {
*head = temp->next; // 更新头节点为下一个节点
free(temp); // 释放原头节点内存
return;
}// 查找要删除的节点
while (temp != NULL && temp->data != key) {
prev = temp; // 更新前驱指针
temp = temp->next; // 移动到下一个节点
}// 如果没有找到要删除的节点
if (temp == NULL) return;// 断开前驱节点与目标节点的连接
prev->next = temp->next; // 将前驱节点的next指向目标节点的next
free(temp); // 释放目标节点内存
}// 遍历链表并打印节点数据的函数
void printList(Node* head) {
Node* temp = head; // 临时指针指向头节点
while (temp != NULL) { // 遍历链表
printf("%d -> ", temp->data); // 打印当前节点数据
temp = temp->next; // 移动到下一个节点
}
printf("NULL\n"); // 输出链表结束标志
}// 主函数
int main() {
Node* head = NULL; // 初始化头节点为空// 插入节点
insertAtHead(&head, 1); // 在头部插入1
insertAtHead(&head, 2); // 在头部插入2
insertAtTail(&head, 3); // 在尾部插入3
insertAtTail(&head, 4); // 在尾部插入4printf("链表内容: ");
printList(head); // 打印链表内容deleteNode(&head, 2); // 删除值为2的节点
printf("删除2后的链表内容: ");
printList(head); // 打印链表内容// 释放链表内存
while (head != NULL) {
Node* temp = head; // 临时指针指向头节点
head = head->next; // 更新头节点为下一个节点
free(temp); // 释放原头节点内存
}return 0; // 程序结束
}