【发布时间】: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;
}
我需要知道如何修改头节点的节点数据
【问题讨论】:
-
您遇到了什么问题?
-
@rpg
head->next = second;很好。它使头节点“指向”第二个节点 -
进一步Singly Linked List of Integers (add, del, print) 可能会有所帮助。
标签: c algorithm data-structures linked-list