c - 修改链表节点数据
问题描述
如何修改节点数据? 我正在尝试修改头节点或任何其他节点的数据内容,但无法做到
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void traverseList(struct Node *ptr)
{
while (ptr != NULL)
{
printf("element is:%d\n", ptr->data);
ptr = ptr->next;
}
}
int main()
{
struct Node *head;
struct Node *second;
struct Node *third;
head = (struct Node *)malloc(sizeof(struct Node));
second = (struct Node *)malloc(sizeof(struct Node));
third = (struct Node *)malloc(sizeof(struct Node));
head->data = 7;
head->next = second;
second->data = 122;
second->next = third;
third->data = 34;
third->next = NULL;
traverseList(head);
free(head);
free(second);
free(third);
return 0;
}
我需要知道如何修改头节点的节点数据
解决方案
您可以编写一个函数来更改列表中索引(又名位置)N 处的节点中的数据。如果第一个元素的索引为零,它可能如下所示:
int update_at(struct Node *ptr, unsigned idx, int data)
{
while (ptr != NULL && idx > 0)
{
ptr = ptr->next;
--idx;
}
if (ptr == NULL) return -1; // Node not found
ptr->data = data;
return 0;
}
并称它为
if (update_at(head, 1, 42)) // Update node at index 1
{
// Update failed - add some error handling
...
}
推荐阅读
- python - jinja2 模板中的 \n 会产生问题吗?
- javascript - 文件由 resteasy 返回,带有额外的字节
- java - 将所需变量传递给所有代码的最佳设计模式
- spring - Spring Cloud Data Flow REST API 组成的任务参数未传递给子任务
- php - ajax 调用返回 NULL
- google-cloud-platform - 如何在具有多个 for 循环的 Airflow DAG 中构建动态工作流?
- r - 如何更改数据框的格式
- ios - Xcode 错误:“'AppDelegate' 类型的值没有成员 'receiveBatteryLevel' Flutter 官方 Flutter 平台频道示例
- javascript - 如何在 StackBlitz 上安装 npm 包?
- flutter - 根据当前时间在 ListTile 中突出显示时间表