我遇到了段错误,但我不知道问题出在哪里。
#include "stdio.h"
#include "stdlib.h"
struct node {
int data;
struct node *next;
};
struct node *head = NULL;
struct node * curr;
struct node * newNode;
void createList(){
int data,n , i ;
scanf("%d",&n);
for (i = 0 ; i < n ;i++){
scanf("%d",&data);
curr = head;
newNode = (struct node*)malloc(sizeof(struct node));
newNode->data=data;
newNode->next=NULL;
if ( curr == NULL){
head = newNode;
}else
while (curr->next != NULL){
curr = curr->next;
}
curr->next = newNode;
}
}
int main(int argc, char const *argv[])
{
createList();
return 0;
}
请问你知道在哪里吗?
第一次迭代很好,但是当 i = 1
时,出现错误。
最佳答案
对齐不足以在 C 中生成 block 代码;-)
需要牙套。没有它,语句 curr->next = newNode;
位于 else
block 之外,这不是您想要的。
if ( curr == NULL){
head = newNode;
}
else {
while (curr->next != NULL){
curr = curr->next;
}
curr->next = newNode;
}
关于c - 链表段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30311787/