用C语言实现对链表中数据的更改
时间: 2024-05-04 16:15:19 浏览: 16
以下是实现对链表中数据的更改的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
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;
}
// 在链表末尾插入节点
void insertNode(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
// 如果链表为空,直接将新节点作为头节点
*head = newNode;
} else {
// 找到链表末尾节点,将新节点插入其后面
struct Node* lastNode = *head;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
lastNode->next = newNode;
}
}
// 打印链表中所有节点的值
void printNodes(struct Node* head) {
printf("List: ");
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
// 更改链表中指定位置节点的值
void modifyNode(struct Node** head, int position, int data) {
if (*head == NULL) {
// 如果链表为空,无法进行更改操作
printf("Error: the list is empty!\n");
} else {
struct Node* currentNode = *head;
int currentPosition = 1;
while (currentNode != NULL && currentPosition < position) {
// 找到指定位置的节点
currentNode = currentNode->next;
currentPosition++;
}
if (currentNode == NULL) {
// 如果指定位置超出链表长度,无法进行更改操作
printf("Error: the position is out of range!\n");
} else {
// 修改节点的值
currentNode->data = data;
}
}
}
int main() {
// 创建链表,并在末尾插入节点
struct Node* head = NULL;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
insertNode(&head, 4);
// 打印链表中所有节点的值
printNodes(head);
// 更改链表中指定位置节点的值
modifyNode(&head, 2, 5);
// 打印链表中所有节点的值
printNodes(head);
return 0;
}
```
在上面的代码中,我们使用了 `modifyNode()` 函数来实现对链表中指定位置节点的值进行更改。该函数首先检查链表是否为空,如果为空则无法进行更改操作;否则,它会遍历链表以找到指定位置的节点。如果指定位置超出了链表长度,则无法进行更改操作。如果找到了指定位置的节点,则修改该节点的值。