I'm trying to reverse this linked-list but after giving input it gives output Segmentation fault (core dumped) while printing the list. This only happened when I declare 4th pointer before that it was working fine when there were only three pointers 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;
}
I understand segmentation fault error still can't figure which part is actually causing the error.
CodePudding user response:
You need to initialize head
to 0. Pointers are not initialized by default. Otherwise, it works fine.
CodePudding user response:
head
is uninitialized, because pointer aren't initialized by default