C语言链表的完整代码
时间: 2024-03-13 17:39:03 浏览: 33
以下是C语言链表的完整代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node* next;
};
// 定义链表头指针
struct Node* head = NULL;
// 在链表尾部插入节点
void insert(int data) {
// 创建新节点
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = data;
new_node->next = NULL;
// 如果链表为空,将新节点作为头节点
if (head == NULL) {
head = new_node;
return;
}
// 遍历链表,找到尾节点
struct Node* tail = head;
while (tail->next != NULL) {
tail = tail->next;
}
// 将新节点插入到尾节点后面
tail->next = new_node;
}
// 在链表中删除节点
void delete(int data) {
// 如果链表为空,直接返回
if (head == NULL) {
return;
}
// 如果要删除的节点是头节点,直接将头指针指向下一个节点
if (head->data == data) {
head = head->next;
return;
}
// 遍历链表,找到要删除的节点的前一个节点
struct Node* prev = head;
while (prev->next != NULL && prev->next->data != data) {
prev = prev->next;
}
// 如果找到了要删除的节点的前一个节点,将其指向下下一个节点
if (prev->next != NULL) {
prev->next = prev->next->next;
}
}
// 遍历链表,打印每个节点的值
void print() {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
// 在链表尾部插入节点
insert(1);
insert(2);
insert(3);
// 打印链表
printf("链表:");
print();
// 删除节点
delete(2);
// 打印链表
printf("删除节点后的链表:");
print();
return 0;
}
```