我遇到了细分错误,我不知道问题出在哪里。
#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
时出现错误。
答案 0 :(得分:5)
对齐不足以在C中创建块代码; - )
需要大括号。没有它,语句curr->next = newNode;
就在else
块之外,这不是你想要的。
if ( curr == NULL){
head = newNode;
}
else {
while (curr->next != NULL){
curr = curr->next;
}
curr->next = newNode;
}