这是链表程序,没有错误,但输出未正确显示 没有错误,但我认为逻辑不行,不使用函数就可以实现这个,只需要逻辑。
struct node * c;
struct node * head;
int n, i = 0;
scan("%d", & n);
if (n < 10) {
for (i = 0; i < n; i++) {
struct node * p;
p = (struct node * ) malloc(size of (struct node));
scan("%d", & p - > data);
p - > next = NULL;
c = NULL;
head = NULL;
if (head == NULL) {
head = p;
} else {
c = head;
while (c - > next != NULL) {
c = c - > next;
}
c - > next = p;
print("%d", c - > next);
struct node * d = head;
while (d != NULL) {
print("%d", d - > data);
d = d - > next;
}
}
}
这是链表程序,我添加了代码部分而不是整个 block
输入 10 20 30 时的预期结果 输出 10->20->30
最佳答案
我看到的主要问题。
head = NULL;
您每次在 for 循环内都将 head
初始化为 NULL
。
您应该在声明时进行初始化。
struct node * head = NULL;
还有
将打印代码移到 for
循环之外。
struct node * d = head;
while (d != NULL) {
print("%d", d - > data);
d = d - > next;
}
关于c - 如何修复此代码中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55843433/