首页 > 解决方案 > 修改链表节点数据

问题描述

如何修改节点数据? 我正在尝试修改头节点或任何其他节点的数据内容,但无法做到

#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;
}

我需要知道如何修改头节点的节点数据

标签: calgorithmdata-structureslinked-list

解决方案


您可以编写一个函数来更改列表中索引(又名位置)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
    ...
}

推荐阅读