Reputation: 759
I am studying how to insert node at the beginning and I came through this code which I am unable to understand.
I am not getting the print function .
typedef struct node
{
int data;
struct node *next;
} Node;
Node *head;
void insert(int x)
{
Node *temp=(Node*)malloc(sizeof(Node));
temp->data=x;
temp->next=head;
head=temp;
}
void print()
{
Node *temp=head;
printf("List is:");
while(temp!=NULL) //Unable to understand this statement as how will the loop terminate?
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
Upvotes: 1
Views: 76
Reputation: 8589
Indentation on the Question is a mess.
But the print function is:
void print() {
Node *temp=head;
printf("List is:");
while(temp!=NULL) {
printf("%d ",temp->data);
temp=temp->next;
}
}
If head==NULL
then temp==NULL
at the start and the loop will terminate immediately.
If head!=NULL
then temp!=NULL
at the start and the data for the head element will be output.
The line temp=temp->next;
will then make temp
point to the next Node
in the list and the loop will advance.
If there's only on Node
in the list the loop will then terminate.
Otherwise it will print the data for that next element and the line temp=temp->next
will move to the third Node
(if any).
And so on...
NB: The line Node *head;
is not recommended. It will be initialized to NULL
because it has static storage duration. But Node *head=NULL;
is recommended for future-proofing and readability.
Upvotes: 0
Reputation: 236
A C-Program need a main function to start with. If you want to test the code above, you need to add a main function to initialize head to NULL at start, call insert() several times and print() to check the results.
Upvotes: 0
Reputation: 19874
Assume your linked list looks like
a->b->c->d
|
|
head
So now we use a temporary variable
temp = head;
and
while(temp != NULL)
{
//Keep moving temp
printf("%d\n",temp->x);
temp = temp->next;
}
So head
is never moved and it is just the temporary pointer which is moved till end of the list the end of the list is got when we reach temp = NULL
a->b->c->d
|
|
temp = head
temp = temp->next;
a->b->c->d
| |
| |
head temp
Repeating the above move until temp = NULL
which is TRUE when the last node contents are printed and we do temp = temp->next;
Upvotes: 2