链表是一种常见的数据结构,用于动态存储数据。它由一系列节点组成,每个节点包含数据部分和指向下一个节点的指针。链表可以动态增长或缩减,非常适合需要频繁插入和删除操作的场景。
链表的基本类型
- 单链表:每个节点只包含一个指向下一个节点的指针。
- 双链表:每个节点包含两个指针,分别指向前一个节点和后一个节点。
- 循环链表:链表的最后一个节点指向第一个节点,形成一个环。
单链表的实现
以下是一个简单的单链表在C语言中的实现示例,包括创建链表、插入节点、删除节点和打印链表的功能。
节点结构体定义
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data; // 数据部分
struct Node* next; // 指向下一个节点的指针
} Node;
创建新节点
// 创建新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
在链表头部插入节点
// 在链表头部插入新节点
void insertAtHead(Node** head, int data) {
Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}
在链表尾部插入节点
// 在链表尾部插入新节点
void insertAtTail(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
删除节点
// 删除链表中指定数据的节点
void deleteNode(Node** head, int data) {
Node* temp = *head;
Node* prev = NULL;
// 如果要删除的节点是头节点
if (temp != NULL && temp->data == data) {
*head = temp->next;
free(temp);
return;
}
// 查找要删除的节点
while (temp != NULL && temp->data != data) {
prev = temp;
temp = temp->next;
}
// 如果没有找到节点
if (temp == NULL) return;
// 断开节点
prev->next = temp->next;
free(temp);
}
打印链表
// 打印链表
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
主函数
int main() {
Node* head = NULL;
insertAtHead(&head, 1);
insertAtHead(&head, 2);
insertAtHead(&head, 3);
printf("链表内容: ");
printList(head);
insertAtTail(&head, 4);
printf("在尾部插入4后: ");
printList(head);
deleteNode(&head, 2);
printf("删除值为2的节点后: ");
printList(head);
return 0;
}
总结
以上是一个基本的单链表的实现示例。链表是非常灵活的数据结构,可以根据需求进行扩展和修改。例如,可以实现双向链表、循环链表,或者在链表中加入更多的操作方法,如排序、查找等。在实际应用中,选择合适的数据结构和算法,可以大大提高程序的效率和性能。
7752

被折叠的 条评论
为什么被折叠?



