In the below code, I am trying to insert a node after a particular node. In the function, I will be giving as input the address of the previous node after which I want to insert the new node. The problem is in the 10th line of function insertAfter() - it says I cannot access *prev_ref->next.
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
void push(struct node **head_ref, int data)
{
struct node* newNode = (struct node*)malloc(sizeof(struct node)) ;
newNode->next= *head_ref;
newNode->data= data;
*head_ref= newNode;
}
void insertAfter(struct node **prev_ref, int data)
{
if(*prev_ref==NULL)
{
printf("prev ref cant be null");
return;
}
struct node * newNode;
newNode = (struct node*)malloc(sizeof(struct node)) ;
newNode->next= *prev_ref->next;
newNode->data= data;
*prev_ref->next= newNode;
}
void printList(struct node *node)
{
while (node != NULL)
{
printf(" %d ", node->data);
node = node->next;
}
}
main()
{
struct node* head = NULL;
push(&head, 7);
push(&head, 1);
insertAfter(&head, 8);
printf("\n Created Linked list is: ");
printList(head);
getchar();
return 0;
}
struct nodeand the complete compiler error message.