我遇到了分段错误,我不知道问题出在哪里.
#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;
}
Run Code Online (Sandbox Code Playgroud)
你能搞清楚在哪里吗?第一次迭代很好,但是什么时候i = 1有错误.
对齐不足以在C中制作代码块 ;-)
需要大括号.没有它,声明curr->next = newNode;就在else块之外而不是你想要的.
if ( curr == NULL){
head = newNode;
}
else {
while (curr->next != NULL){
curr = curr->next;
}
curr->next = newNode;
}
Run Code Online (Sandbox Code Playgroud)