【问题标题】:modifying linked list node data修改链表节点数据
【发布时间】:2021-04-27 14:19:30
【问题描述】:

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

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

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

【问题讨论】:

标签: c algorithm data-structures linked-list


【解决方案1】:

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

【讨论】:

  • 或while (ptr &amp;&amp; idx--) ptr = ptr-&gt;next; ...对于不可读的人群:)
  • 是的。更紧凑,但我决定“拼出来”。无论如何,我怀疑可执行文件会有很大(如果有的话)差异。
猜你喜欢
  • 2019-11-17
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多