【发布时间】:2021-04-30 12:03:35
【问题描述】:
创建了一个结构节点指针并用 null 初始化它,然后传递它来创建一个链表,如果我们用 malloc 初始化头指针,它就可以工作,但不能这样工作,谁能说我错在哪里??
#include <stdio.h>
#include <stdlib.h>
int i;
struct node
{
int data;
struct node *ptr;
};
void create(struct node *head, int n)
{
for (i = 0; i < n; i++)
{
struct node *p = (struct node *)malloc(sizeof(struct node));
scanf("%d", &p->data);
if (head == NULL)
head = p;
else
{
head->ptr = p;
}
}
}
void display(struct node *head)
{
struct node *p = head;
if (head == NULL)
{
printf("Empty Linked List");
return;
}
else
{
while (p != NULL)
{
printf("%d", head->data);
p = p->ptr;
}
}
}
int main()
{
struct node *head = NULL;
int n;
scanf("%d", &n);
create(head, n);
display(head);
return 0;
}
【问题讨论】:
-
那么问题出在哪里?
struct node定义在哪里? -
@MrMischievousX This if (head->ptr == NULL) head->data = p->data;否则 { 头->ptr = p; } 没有意义并产生内存泄漏。
-
@VladfromMoscow 你能纠正我吗?
-
例如输入
3 1 2 3的期望输出是什么? -
@MikeCAT 1 2 3 应该输出
标签: c struct linked-list singly-linked-list function-definition