c语言链表修改原有数据的代码
时间: 2023-08-12 22:42:45 浏览: 53
下面是一个简单的 C 语言链表修改原有数据的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int data;
struct ListNode* next;
} ListNode;
void modifyList(ListNode* head, int target, int newValue) {
ListNode* current = head;
while (current) {
if (current->data == target) {
current->data = newValue;
return;
}
current = current->next;
}
}
int main() {
// 创建链表
ListNode* head = (ListNode*)malloc(sizeof(ListNode));
head->data = 1;
head->next = NULL;
ListNode* second = (ListNode*)malloc(sizeof(ListNode));
second->data = 2;
second->next = NULL;
head->next = second;
ListNode* third = (ListNode*)malloc(sizeof(ListNode));
third->data = 3;
third->next = NULL;
second->next = third;
// 修改链表中的数据
modifyList(head, 2, 4);
// 输出链表中的数据
ListNode* current = head;
while (current) {
printf("%d\n", current->data);
current = current->next;
}
// 释放链表所占用的内存
current = head;
while (current) {
ListNode* temp = current;
current = current->next;
free(temp);
}
return 0;
}
```
在上面的代码中,`modifyList` 函数可以接收一个链表的头结点指针、需要修改的数值、以及新的数值作为参数。函数会遍历整个链表,找到第一个值为 `target` 的节点,并将其值修改为 `newValue`。如果链表中不存在值为 `target` 的节点,则不做任何修改。
在 `main` 函数中,我们创建了一个简单的链表,然后调用 `modifyList` 函数将链表中值为 2 的节点修改为 4。最后,我们输出修改后的链表,并释放链表所占用的内存。