1.下面是一个简单的例子,展示链表的如何创建、插入和删除链表节点:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
struct node* create_list() {
struct node* head = (struct node*)malloc(sizeof(struct node));
head->next = NULL;
return head;
}
void insert_node(struct node* head, int value) {
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = value;
new_node->next = head->next;
head->next = new_node;
}
void delete_node(struct node* head, int value) {
struct node* p = head;
while (p->next != NULL) {
if (p->next->data == value) {
struct node* tmp = p->next;
p->next = tmp->next;
free(tmp);
break;
}
p = p->next;
}
}
void print_list(struct node* head) {
struct node* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
struct node* head = create_list();
insert_node(head, 1);
insert_node(head, 2);
insert_node(head, 3);
printf("Initial List: ");
print_list(head);
delete_node(head, 2);
printf("After Deletion: ");
print_list(head);
return 0;
}
2.静态申请内存的方式。代替 malloc 分配的内存空间。
使用静态申请内存的方式可以通过在定义结构体变量时,直接定义一段固定大小的数组,然后使用这个数组来代替 malloc 分配的内存空间。下面是一个示例代码,其中使用了一个全局数组 node_pool
来作为静态内存池,每个节点大小为 sizeof(struct node)
。
#include <stdio.h>
#include <stdlib.h>
#define NODE_POOL_SIZE 100 // 内存池大小
struct node {
int data;
struct node* next;
};
struct node node_pool[NODE_POOL_SIZE];
int node_pool_index = 0;
struct node* create_list() {
struct node* head = &node_pool[node_pool_index++];
head->next = NULL;
return head;
}
void insert_node(struct node* head, int value) {
struct node* new_node = &node_pool[node_pool_index++];
new_node->data = value;
new_node->next = head->next;
head->next = new_node;
}
void delete_node(struct node* head, int value) {
struct node* p = head;
while (p->next != NULL) {
if (p->next->data == value) {
struct node* tmp = p->next;
p->next = tmp->next;
tmp->next = NULL;
node_pool_index--; // 回收内存
break;
}
p = p->next;
}
}
void print_list(struct node* head) {
struct node* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
node_pool_index = 0; // 初始化内存池索引
struct node* head = create_list();
insert_node(head, 1);
insert_node(head, 2);
insert_node(head, 3);
printf("Initial List: ");
print_list(head);
delete_node(head, 2);
printf("After Deletion: ");
print_list(head);
return 0;
}