【发布时间】:2022-01-09 13:31:05
【问题描述】:
我已经解释了我目前陷入困境的地方。
下面这个结构是我的节点。
struct node {
int data;
struct node *next;
}
struct node *head;
我已经为头节点分配了内存。
head = malloc(sizeof(struct node));
并通过
创建了一堆与之链接的其他节点struct node *temp;
for (int i=0; i < no_of_nodes - 1; i++)
{
struct node *n = malloc(sizeof(struct node));
temp -> next = n;
printf("Enter Node %d data : ", i+1);
scanf("%d", &(n -> data));
temp = n;
}
temp -> next = NULL;
然后是我的printNodes函数
void printNodes(struct node *n)
{
//printf("%d", n -> data);
while(n != NULL)
{
if (n -> next != NULL)
printf("%d%s", n -> data, " -> ");
else
printf("%d%s", n -> data, " -> NULL\n");
n = n->next;
}
}
输出将如下所示:6 -> 7 -> 8 -> 9 -> 3 -> NULL
现在,我正在尝试在头节点插入一个节点,即它成为头节点,原始头成为第二个节点。
printf("Enter the head position (obviously 0) : ");
scanf("%d", &pos);
insertNode(head, pos);
printNodes(head);
插入节点函数:
void insertNode (struct node *head, int pos)
{
struct node *n;
n = malloc(sizeof(struct node));
printf("Enter the Node data : ");
scanf("%d", &(n -> data));
if (pos == 0)
{
printf("Pos was 0, so HEAD\n");
n -> next = head;
head = n;
printNodes(head);
}
}
好的,所以问题是,printNodes(head) 实际上按预期打印..
但是
printNodes(head);after insertNodes(head, pos) 不打印更新的链接列表,
为什么头部没有更新?
我哪里做错了?
我得到的输出是, 输出:
输入Head位置(显然是0):0
输入节点数据:34
Pos 为 0,所以 HEAD
34 -> 6 -> 7 -> 8 -> 9 -> 3 -> NULL [from printNodes(head) inside insertNodes(head, pos)]
6 -> 7 -> 8 -> 9 -> 3 -> NULL [from printNodes(head) after insertNodes(head, pos)]
如果有人想查看完整代码, here你去。
任何帮助表示赞赏.. 提前谢谢你。
【问题讨论】:
标签: c struct pass-by-reference singly-linked-list function-definition