I have implemented a short linked list code to add to the beginning of the list.
However the head always contained NULL
. I really couldn't get why its behaving in this way. Any help is appreciated ! Below is the code :
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int iData;
struct node *next;
} Node;
void add2Beg(Node* head, int num);
int main(int argc, char const *argv[])
{
Node *head = NULL;
add2Beg(head, 5);
if (head == NULL)
printf("nothing in head !!!\n");
else{
printf("not null\n");
}
add2Beg(head, 15);
return 0;
}
//adds to the beginning of the linked list
void add2Beg(Node* head, int num)
{
//create a temporary location to hold the new entry
Node* temp = (Node *)malloc(sizeof(Node));
temp->iData = num;
if(head == NULL)
{
head = temp;
printf("inside add2Beg\n");
printf("%d\n", head->iData);
head->next = NULL;
printf("exiting add2Beg\n");
}
else
{
temp->next = head;
printf("%p\n", temp->next);
head = temp;
}
}