#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
struct Node {
int data;
struct Node* next;
};
// 在指定位置插入新节点的函数
void insertNode(struct Node** head, int position, int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if (position == 1) {
newNode->next = *head;
*head = newNode;
return;
}
struct Node* current = *head;
for (int i = 1; i < position - 1 && current != NULL; i++) {
current = current->next;
}
if (current != NULL) {
newNode->next = current->next;
current->next = newNode;
} else {
free(newNode);
printf("位置无效,无法插入节点。\n");
}
}
// 创建新节点的辅助函数
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 打印链表的辅助函数
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
// 释放链表内存的辅助函数
void freeList(struct Node* head) {
struct Node* current = head;
struct Node* nextNode;
while (current != NULL) {
nextNode = current->next;
free(current);
current = nextNode;
}
}
int main() {
struct Node* head = createNode(1);
head->next = createNode(2);
head->next->next = createNode(3);
printf("原始链表: ");
printList(head);
insertNode(&head, 2, 4);
printf("插入节点后的链表: ");
printList(head);
freeList(head);
return 0;
}
- 定义链表节点结构:
struct Node
包含一个 int
类型的 data
成员用于存储数据,以及一个 struct Node*
类型的 next
成员用于指向下一个节点。
insertNode
函数:
- 首先分配新节点的内存,并初始化其
data
和 next
。
- 如果
position
为1,将新节点插入到链表头部,更新 head
。
- 否则,遍历链表到
position - 1
的位置。如果找到了该位置(current
不为 NULL
),则将新节点插入到该位置之后;否则,释放新节点并提示位置无效。
- 辅助函数:
createNode
函数用于创建新节点并初始化其数据和指针。
printList
函数用于打印链表。
freeList
函数用于释放链表占用的内存。
main
函数:
- 创建一个简单的链表,调用
insertNode
函数在指定位置插入新节点,然后打印链表并释放链表内存。