用c语言写出链表的初始化,插入,删除,打印,销毁
时间: 2023-09-28 07:09:51 浏览: 50
链表是一种常见的数据结构,它由一系列节点组成,每个节点包含一个数据域和一个指向下一个节点的指针。在C语言中,我们可以使用结构体来表示节点,并用指针来连接它们。下面是链表的初始化、插入、删除、打印和销毁的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data; // 数据域
struct Node* next; // 指向下一个节点的指针
};
// 初始化链表
void initList(struct Node** head) {
*head = NULL; // 头节点指针置空
}
// 插入节点
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;
} else { // 如果链表不为空,遍历到链表末尾,将新节点插入
struct Node* cur = *head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newNode;
}
}
// 删除节点
void deleteNode(struct Node** head, int data) {
struct Node* cur = *head;
struct Node* prev = NULL;
// 遍历链表查找要删除的节点
while (cur != NULL && cur->data != data) {
prev = cur;
cur = cur->next;
}
if (cur == NULL) { // 要删除的节点不存在
printf("Node not found!\n");
return;
}
if (prev == NULL) { // 要删除的节点为头节点
*head = cur->next;
} else { // 要删除的节点不是头节点
prev->next = cur->next;
}
free(cur); // 释放要删除的节点
}
// 打印链表
void printList(struct Node* head) {
struct Node* cur = head;
while (cur != NULL) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
// 销毁链表
void destroyList(struct Node** head) {
struct Node* cur = *head;
while (cur != NULL) {
struct Node* temp = cur;
cur = cur->next;
free(temp);
}
*head = NULL;
}
int main() {
struct Node* head;
initList(&head);
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
printf("Original list: ");
printList(head);
deleteNode(&head, 2);
printf("After deleting 2: ");
printList(head);
destroyList(&head);
return 0;
}
```
这段代码实现了链表的基本操作,包括初始化、插入、删除、打印和销毁。你可以根据自己的需要修改它,实现更加高级的链表操作。