摘要:#include #include // 定义节点结构 typedef struct Node { int data; // 数据域 struct Node* next; // 指针域 } Node; // 初始化链表,返回头节点 Node* initList() { Node* h
#include
#include
// 定义节点结构
typedef struct Node {
int data; // 数据域
struct Node* next; // 指针域
} Node;
// 初始化链表,返回头节点
Node* initList() {
Node* head = (Node*)malloc(sizeof(Node));
if (head == NULL) {
printf("内存分配失败n");
return NULL;
}
head->data = 0; // 可以是任意值,也可以不赋值
head->next = NULL;
return head;
}
// 头部插入新节点
void insertAtHead(Node* head, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("内存分配失败n");
return;
}
newNode->data = data;
newNode->next = head->next;
head->next = newNode;
}
// 尾部插入新节点
void insertAtTail(Node* head, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("内存分配失败n");
return;
}
newNode->data = data;
newNode->next = NULL;
Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
// 在指定位置插入新节点,位置从0开始计数
void insertAtPosition(Node* head, int data, int position) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("内存分配失败n");
return;
}
newNode->data = data;
Node* temp = head;
for (int i = 0; i < position && temp != NULL; i++) {
temp = temp->next;
}
if (temp == NULL) {
printf("位置超出范围n");
free(newNode);
return;
}
newNode->next = temp->next;
temp->next = newNode;
}
// 删除指定位置的节点,位置从0开始计数
void deleteAtPosition(Node* head, int position) {
Node* temp = head;
for (int i = 0; i < position && temp->next != NULL; i++) {
temp = temp->next;
}
if (temp->next == NULL) {
printf("位置超出范围n");
return;
}
Node* deleteNode = temp->next;
temp->next = deleteNode->next;
free(deleteNode);
}
// 遍历链表并打印每个节点的数据
void traverseList(Node* head) {
Node* temp = head->next; // 跳过头节点
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULLn");
}
// 释放链表
void freeList(Node* head) {
Node* temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
}
int main() {
Node* list = initList();
insertAtHead(list, 10);
insertAtTail(list, 20);
insertAtPosition(list, 15, 1);
traverseList(list);
deleteAtPosition(list, 1);
traverseList(list);
freeList(list);
return 0;
}