基于链表的简单数据结构实现
在这篇文章中,我们将探讨一个简单的链表实现,包括链表的创建、插入、删除、查找和打印等基本操作。链表是一种灵活的数据结构,常用于动态存储和管理数据。以下是我们实现的链表的具体细节。
1. 头文件定义
首先,我们定义了一个头文件 `Lk.h`,其中包含了链表节点的结构体和相关函数的声明。
#pragma once
#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int data;
struct node* next;
}*node_ptr;
extern node_ptr node_creat(int value);
extern void insert_node_head(node_ptr &h, int data);
extern void insert_node_tail(node_ptr &h, int data);
extern void delete_node(node_ptr &h, int data);
extern node_ptr find_node(node_ptr &h, int data);
extern void print_list(node_ptr &h);
extern void destroy_list(node_ptr &h);
结构体定义
我们定义了一个 `node` 结构体,包含两个成员:
- `data`: 存储节点的数据。
- `next`: 指向下一个节点的指针。
2. 源文件实现
在源文件 `Lk.c` 中,我们实现了链表的各种操作。
2.1 创建节点
node_ptr node_creat(int value) {
node_ptr p = (node_ptr)malloc(sizeof(node));
if (p == NULL) {
printf("node_creat call fail\n");
return NULL;
}
p->data = value;
p->next = NULL;
return p;
}
`node_creat` 函数用于创建一个新节点并初始化其数据和指针。
2.2 头插法
void insert_node_head(node_ptr &h, int data) {
node_ptr p = node_creat(data);
if (p == NULL) {
printf("node_creat function call failure\n");
return;
}
printf("头插入%d\n", data);
p->next = h;
h = p;
}
`insert_node_head` 函数实现了在链表头部插入节点的功能。
2.3 尾插法
void insert_node_tail(node_ptr &h, int data) {
node_ptr p = node_creat(data);
if (h == NULL) {
h = p;
printf("尾插入%d\n", p->data);
} else {
node_ptr temp = h;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = p;
printf("尾插入%d\n", p->data);
}
}
`insert_node_tail` 函数用于在链表尾部插入节点。
2.4 删除节点
void delete_node(node_ptr &h, int data) {
if (h == NULL) {
printf("node is empty\n");
return;
}
node_ptr temp = NULL;
node_ptr prev = NULL;
temp = h;
while (temp != NULL && temp->data == data) {
prev = temp;
temp = temp->next;
}
prev->next = temp->next;
free(temp);
}
`delete_node` 函数用于根据值删除节点。
2.5 查找节点
node_ptr find_node(node_ptr &h, int data) {
node_ptr p = h;
while (p != NULL) {
if (p->data == data) {
return p;
}
p = p->next;
}
return NULL;
}
`find_node` 函数用于查找指定值的节点。
2.6 打印链表
void print_list(node_ptr &h) {
node_ptr p = h;
while (p != NULL) {
printf("%d\n", p->data);
p = p->next;
}
printf("打印完毕\n");
}
`print_list` 函数用于打印链表中的所有节点。
2.7 销毁链表
void destroy_list(node_ptr &h) {
node_ptr p = h;
node_ptr q = NULL;
while (p != NULL) {
q = p->next;
free(p);
p = q;
}
printf("释放完毕\n");
}
`destory_list` 函数用于释放链表的所有节点,避免内存泄漏。
3. 主函数在 `main.c` 文件中,我们测试了链表的各项功能。
#include "Lk.h"
int main() {
node_ptr head = NULL;
// 头插法
for (int i = 0; i < 10; i++) {
insert_node_head(head, i);
}
// 尾插法
for (int i = 10; i < 20; i++) {
insert_node_tail(head, i);
}
print_list(head);
destroy_list(head);
return 0;
}