c语言链表
时间: 2023-06-21 11:16:25 浏览: 52
链表是一种数据结构,可以用来在内存中动态存储和访问数据。在C语言中,链表可以通过结构体和指针来实现。下面是一个简单的链表示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node* next;
};
// 创建链表节点
struct Node* create_node(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
return node;
}
// 插入节点到链表尾部
void insert_node(struct Node** head, int data) {
struct Node* node = create_node(data);
if (*head == NULL) {
*head = node;
return;
}
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = node;
}
// 删除链表中的节点
void delete_node(struct Node** head, int data) {
struct Node* current = *head;
struct 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);
}
// 遍历链表并输出节点数据
void print_list(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
// 主函数
int main() {
struct Node* head = NULL;
insert_node(&head, 1);
insert_node(&head, 2);
insert_node(&head, 3);
insert_node(&head, 4);
print_list(head);
delete_node(&head, 3);
print_list(head);
return 0;
}
```
这个示例中创建了一个链表结构体`Node`,包含一个整数类型的`data`和一个指向下一个节点的指针`next`。接着定义了几个函数,包括创建节点、插入节点、删除节点和遍历链表等。在主函数中,先插入了几个节点,然后遍历链表并输出节点数据。最后删除了一个节点,再次输出链表数据。