链表是一种常见的基础数据结构,它由节点组成,每个节点包含数据域和指针域。以下是单链表的基本实现:
// 定义链表节点结构
struct Node {
int data;
struct Node* next;
};
// 创建新节点
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 在链表头部插入节点
struct Node* insertAtHead(struct Node* head, int data) {
struct Node* newNode = createNode(data);
newNode->next = head;
return newNode;
}
主要操作包括:
- 插入节点(头部、尾部、中间位置)
- 删除节点
- 查找节点
- 遍历链表