>>what is the difference between ptr1 pointing and ptr1->link pointing?
ptr1 is a pointer to a structure called Node. link is a member of the Node structure, and it's a pointer to a Node too. ptr1 is dereferenced so that you can access the members of the Node structure and then the value of link is taken. Think of it as a big box, the big box is ptr1, you reach into the box with the arrow operator -> and grab a smaller box called link.
>>why the command "ptr1 = ptr1->link;"
This sets ptr1 to be ptr1->link, which basically moves ptr1 to the next node in the list.
Code:
ptr1
|
1->2->3->4
ptr1 = ptr1->link;
ptr1
|
1->2->3->4
>>why is it necessary to allocate memory to what ptr2-> is pointing at even when it points at nothing ?
It points at nothing, but then you want to make a new node there, so you allocate memory for one.
>>At which command does ptr2 start to point at something ??
This one
Code:
ptr2 = (nodePtr) malloc (sizeof (Node));
>>why make ptr1->link = NULL ?
NULL is the most common marker for the end of a linked list because no valid node will be NULL, so you can do something like this to walk the list and be sure that you'll stop when you want to
Code:
for (ptr2 = ptr1; ptr2 != NULL; ptr2 = ptr2->link)
{
printf("%d\n", ptr2->data);
}
I would have done it differently so that it wasn't so confusing
Code:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *link;
};
typedef struct node *pnode;
int main(void)
{
int i;
pnode head = 0; /* Link to the beginning of the list */
pnode np; /* Scratch link, used to build the list and walk it */
for (i = 0; i < 5; i++) /* Add 5 nodes */
{
np = malloc(sizeof(struct node)); /* Make a new node */
np->data = i; /* Set the value */
/* Add the new node to the front of the list like so */
/* 1. Set the link to the beginning of the list */
/* 2. Reset head to the new node */
np->link = head;
head = np;
}
/* Print the entire list */
for (np = head; np != 0; np = np->link)
{
printf("%d ", np->data);
}
return 0;
}
The effect is like this
Code:
head
|
~
head
|
0
head
|
1 0
head
|
2 1 0
head
|
3 2 1 0
head
|
4 3 2 1 0