Even though I am assigning the newly created node, the head always points to NULL only. when I debugged, at head = temp it's getting the correct value. But after I get exit from the function, I got NULL in head pointer. I supposed malloc will allocate global memory. Can anyone pls help what is the mistake that I am doing here? I am getting "list is empty" after I enter any input
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
void display(struct Node *head);
void addNode(struct Node *head,int data);
int main(void) {
struct Node *head = NULL;
int data;
printf("Enter the data");
scanf("%d", &data);
addNode(head,data);
display(head);
}
void addNode(struct Node *head,int data) {
struct Node *temp = (struct Node*) malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
if (head == NULL) {
head = temp;
return;
} else {
struct Node *ptr = head;
while (ptr->next != NULL)
ptr = ptr->next;
ptr->next = temp;
}
}
void display(struct Node *head) {
struct Node* ptr;
if (head == NULL)
printf("list is empty");
else {
while (ptr != NULL) {
printf("%d\n", ptr->data);
ptr = ptr->next;
}
}
}