I'm implementing a queue using linked lists in C. Here's my structure -
typedef struct llist node;
struct llist
{
int data;
node *next;
};
I'm facing problem while executing push(). Here's my push() definition -
void push(node *head,int n)
{
if (head==NULL)
{
head=(node *)(malloc((sizeof(node))));
head->data=n;
head->next=NULL;
printf("=>%d\n",head->data);
}
else
{
node *ptr;
ptr=head;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=(node *)(malloc((sizeof(node))));
ptr=ptr->next;
ptr->data=n;
ptr->next=NULL;
}
return;
}
and here's my main() function -
int main()
{
int choice,n;
node *head;
head=NULL;
while(1)
{
printf("Enter your choice -\n1. Push\n2. Pop\n3. Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter element to push: ");
scanf("%d",&n);
push(head,n);
if (head==NULL)//To check if head is NULL after returning from push()
{
printf("Caught here!\n");
}
break;
case 2:
pop(head);
break;
case 3:
return 0;
}
}
}
Now the problem is that after push() exits in case 1, head becomes NULL again, ie, the Caught here! statement does get executed. How is it possible?
push(). To modify the one inmain()you need a double-pointer.push()should bevoid push(node **head, int n)and wherever you useheadinpush()you should be using*headinstead, and you should passpush(&head, n)when you call it.headinmainfunction andheadinpopfunction are two different variables.