用C语言实现单链表的基本操作并注释
时间: 2024-05-19 14:15:54 浏览: 18
/*
* 单链表的基本操作,包括:
* 1. 初始化链表
* 2. 遍历链表
* 3. 插入节点
* 4. 删除节点
*/
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct node {
int data; // 数据域
struct node *next; // 指针域,指向下一个节点
} Node;
// 初始化链表,返回头节点
Node *initList() {
Node *head = (Node*)malloc(sizeof(Node)); // 创建头节点
head->next = NULL; // 头节点的指针域为空
return head;
}
// 遍历链表
void traverseList(Node *head) {
Node *p = head->next; // p指向第一个节点
while (p != NULL) {
printf("%d ", p->data); // 输出节点的数据域
p = p->next; // p指向下一个节点
}
printf("\n");
}
// 插入节点,在第i个位置插入节点,数据域为data
void insertNode(Node *head, int i, int data) {
Node *p = head;
int j = 0;
while (p != NULL && j < i-1) { // 找到第i-1个节点
p = p->next;
j++;
}
if (p == NULL || j > i-1) { // 如果i大于链表长度或小于等于0,插入失败
printf("Insert failed.\n");
return;
}
Node *newNode = (Node*)malloc(sizeof(Node)); // 创建新节点
newNode->data = data; // 设置新节点的数据域
newNode->next = p->next; // 新节点的指针域指向第i个节点
p->next = newNode; // 第i-1个节点的指针域指向新节点
}
// 删除节点,删除第i个节点
void deleteNode(Node *head, int i) {
Node *p = head;
int j = 0;
while (p != NULL && j < i-1) { // 找到第i-1个节点
p = p->next;
j++;
}
if (p == NULL || p->next == NULL || j > i-1) { // 如果i大于链表长度或小于等于0,删除失败
printf("Delete failed.\n");
return;
}
Node *q = p->next; // q指向第i个节点
p->next = q->next; // 第i-1个节点的指针域指向第i+1个节点
free(q); // 释放第i个节点的空间
}
// 主函数
int main() {
Node *head = initList(); // 初始化链表
insertNode(head, 1, 1); // 在第1个位置插入节点
insertNode(head, 2, 2); // 在第2个位置插入节点
insertNode(head, 3, 3); // 在第3个位置插入节点
traverseList(head); // 遍历链表
deleteNode(head, 2); // 删除第2个节点
traverseList(head); // 遍历链表
return 0;
}