在C中打印反向链表时出现分段故障(核心转储)



我试图反转这个链表,但在给出输入后,它在打印列表时给出输出分段错误(核心转储(。这只发生在我之前声明第4个指针时,当只有head、newcode和temp三个指针时它工作正常

#include <stdio.h>
#include <stdlib.h>
int main()
{
struct node
{
int data;
struct node *next;
};
struct node *head, *newnode, *temp;
int choice = 1;
// Creating a linked-list
while (choice)
{
newnode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data: ");
scanf("%d", &newnode->data);
newnode->next = 0;
if (head == 0)
{
head = temp = newnode;
}
else
{
temp->next = newnode;
temp = newnode;
}
printf("Do you want to continue: ");
scanf("%d", &choice);
}
temp = head;
// Reversing the LL
struct node *prevnode, *currentnode, *nextnode;
prevnode = 0;
currentnode = nextnode = head;
while (nextnode != 0)
{
nextnode = nextnode->next;
currentnode->next = prevnode;
prevnode = currentnode;
currentnode = nextnode;
}
head = prevnode;
// Printing the Linked-list
while (prevnode != 0)
{
printf("%d ", prevnode->data);
prevnode = prevnode->next;
}
return 0;
}

我知道分段错误仍然无法确定是哪个部分导致了错误。

您需要将head初始化为0。默认情况下,指针不会初始化。否则,它工作得很好。

head未初始化,因为默认情况下指针未初始化

最新更新