I have started coding Linked list in C. My code is as follows:
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
};
struct node * create(struct node *);
display(struct node *);
int main()
{
struct node *head=NULL;
head = create(head);
display(head);
getch();
return 0;
}
struct node * create(struct node *Head)
{
struct node *temp;
char ch='y';
int i=1;
while(ch=='y')
{
temp=malloc(sizeof(struct node));
temp->data=i*10;
temp->next=Head;
Head=temp;
printf("\nAdded node : %d",Head->data);
printf("\nContinue to add more nodes ? : ");
scanf("%c",&ch);
}
return Head;
}
display(struct node *Head)
{
while(Head!=NULL)
{ printf("%d\t%d\n",Head->data,Head->next);
Head=Head->next;
}
}
The problem that I am facing is that after entering into the function "create" and creating just one node, my program jumps back to main, then jumps to "display" function and then jumps back to function "create" at the line where it asks me whether I want to continue. At this point, when I do enter "y", program just exits! Why this sorta behaviour?? Someone please explain me how the control flows and why is my program going haywire!!!
This happens because when you type in 'y'
and then hit enter, a newline character '\n'
gets buffered and will be read on the next iteration of scanf()
. This will cause while(ch=='y')
to evaluate to false
(since now ch == '\n'
), breaking off the loop.
Normally scanf()
would skip whitespaces and newlines before hitting the expected value. However, when you use the character format %c
, this doesn't happen, as newlines and whitespaces are also valid characters.
You can fix it by using scanf(" %c",&ch);
. The space before %c
will skip any leading backspace or newline characters found on the buffer before actually reading the value.