我试图反转这个链接列表,但是在输入之后,它给出输出分段错误(核心转储),同时打印列表。这只发生在我声明第4指针之前,它运行良好时,只有三个指针头部,新代码,临时。
#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;
}据我所知,分割错误仍然无法判断到底是哪一部分造成了错误。
发布于 2021-11-22 04:19:30
您需要将head初始化为0。默认情况下不初始化指针。否则,它就能正常工作。
发布于 2021-11-22 04:34:56
head未初始化,因为指针在默认情况下未初始化
https://stackoverflow.com/questions/70060775
复制相似问题