【数据结构】单链表---C语言版(全网最最最最细!小白必必必必看!!!有图有真相!)
发布人:shili8
发布时间:2024-11-16 10:09
阅读次数:0
**单链表---C语言版**
**前言**
在计算机科学中,数据结构是指组织和存储数据的方式。单链表是一种常见的线性数据结构,它由一系列结点组成,每个结点包含一个值和一个指向下一个结点的指针。在本文中,我们将详细介绍单链表的定义、特点、操作以及C语言版的实现。
**单链表的定义**
单链表是一种线性数据结构,它由一系列结点组成,每个结点包含两个部分:
* **值域(Value)**: 每个结点存储一个具体的值。
* **指针域(Pointer)**: 每个结点存储一个指向下一个结点的指针。
**单链表的特点**
1. **线性结构**:单链表是一种线性的数据结构,每个结点都有一个前驱结点和一个后继结点。
2. **动态分配内存**:单链表可以动态地分配和释放内存,适合于存储大量的数据。
3. **插入和删除操作**:单链表支持高效的插入和删除操作,只需要改变相应结点的指针域即可。
**C语言版的实现**
下面是C语言版的单链表实现:
c#include <stdio.h>
#include <stdlib.h>
// 结点结构体定义typedef struct Node {
int data; // 值域 struct Node* next; // 指针域} Node;
// 单链表结构体定义typedef struct LinkedList {
Node* head; // 头结点指针} LinkedList;
// 创建一个新结点Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory error
");
return NULL;
}
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// 初始化一个空链表LinkedList* initList() {
LinkedList* list = (LinkedList*)malloc(sizeof(LinkedList));
if (!list) {
printf("Memory error
");
return NULL;
}
list->head = NULL;
return list;
}
// 插入结点到头部void insertHead(LinkedList* list, int value) {
Node* newNode = createNode(value);
if (list->head == NULL) {
list->head = newNode;
} else {
newNode->next = list->head;
list->head = newNode;
}
}
// 插入结点到尾部void insertTail(LinkedList* list, int value) {
Node* newNode = createNode(value);
if (list->head == NULL) {
list->head = newNode;
} else {
Node* current = list->head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 删除头结点void deleteHead(LinkedList* list) {
if (list->head == NULL) {
printf("List is empty
");
return;
}
Node* temp = list->head;
list->head = list->head->next;
free(temp);
}
// 删除尾结点void deleteTail(LinkedList* list) {
if (list->head == NULL) {
printf("List is empty
");
return;
}
if (list->head->next == NULL) {
Node* temp = list->head;
list->head = NULL;
free(temp);
return;
}
Node* current = list->head;
while (current->next->next != NULL) {
current = current->next;
}
Node* temp = current->next;
current->next = NULL;
free(temp);
}
// 打印链表void printList(LinkedList* list) {
Node* current = list->head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("
");
}
**示例代码**
cint main() {
LinkedList* list = initList();
insertHead(list,1);
insertHead(list,2);
insertTail(list,3);
printList(list); // 输出:213 deleteHead(list);
printList(list); // 输出:13 deleteTail(list);
printList(list); // 输出:1 return0;
}
**总结**
在本文中,我们详细介绍了单链表的定义、特点、操作以及C语言版的实现。通过示例代码,读者可以更好地理解单链表的使用和应用。

