程序的控制流没有进入创建列表功能,我无法理解。为什么会这样。
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node *next;
}*head=NULL;
struct Node * createList( int arr[], int n){
head->data = arr[0];
head->next = NULL;
struct Node * last;
last = head;
for(int i=1; i<n; i++){
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = arr[i];
newNode->next = NULL;
last->next = newNode;
last = newNode;
printf("executed ");
}
return head;
}
void Display(struct Node * head){
struct Node * p = head;
while(p!=NULL){
printf("%d ", p->data);
p = p->next;
}
}
int main()
{
int arr[]={2,55,2,6,66};
struct Node * result = createList(arr, 5);
Display(result);
return 0;
}
我在createList函数的for循环中声明了一个cout,但它没有在终端中打印,因此控制没有进入函数,我已经尝试了几种方法,但仍然无法解决这个问题。
1条答案
按热度按时间bf1o4zei1#
您的代码尝试在
createList
中的第一个语句解引用NULL指针:此时
head
是NULL
,所以head->data
没有意义。您应该 * 首先 * 创建(分配)一个节点,然后才分配给它的
data
成员。另外,不应该将
head
定义为全局变量。这应该是createList
的局部变量,因为调用者无论如何都在使用返回的指针,而不是head
。我还将节点创建代码移动到一个单独的函数中-这使代码更具可读性。最后,要填充列表,使用指针指针会很方便,这样你就可以使用相同的代码来设置
head
和设置next
成员: