Linked List question
what does this mean?
void add(struct node **root, int x)
{
struct node *conductor;
if(*root==NULL)
{
(*root)=malloc(sizeof(struct node));
(*root)->x=x;
(*root)->next=NULL ;
}
else
{
conductor = *root;
while(conductor->next!=NULL)
{
conductor = conductor -> next;
} 开发者_Python百科
conductor->next=malloc(sizeof(struct node));
conductor->next->x=x;
conductor->next->next=NULL;
}
}
the conductor=Conductor->next;
what does that mean? I need to feed my curiosity and I want to know if my idea about is true
it is mine, I just want to make sure if my thought on was correct, I am having doubts on my code all the time
A linked-list is constructed by a serie of object, each one pointing to the next element in the list. The line conductor = conductor->next;
just update the conductor
variable (that point to a list element, a struct node
) to point to the next element in the list.
Update: the wikipedia article about linked-list offer good visual representation of a such a data structure.
conductor -> next
is just a way of writing (*conductor).next
.
Since conductor is a pointer to struct, you can't access it's members by conductor.next directly, in this case, it means that conductor
will now point to the next element in the list (the one that conductor->next
pointed to before)
conductor=*root
sets the pointer conductor to point to the first element in the list root
conductor=conductor->next
sets the pointer conductor to point to the next element in the list root.
As compared to an array with length of one, the first line would set a pointer to the 0th element of an array, while the next line would set the pointer to the 1st element. If this does not make sense, you should read up on linked lists, and why you use them compared to say arrays.
According to what you asked:
conductor=conductor->next means that the means that the conductor will move
to the next memory location.
For example :
void insert(struct node **ptr)
{
struct node *tmp;
tmp=*ptr;
tmp=tmp->next;
}
tmp is now pointing to the starting memory location of the linked list as we can point the pointer to anywhere if it is not a const pointer.
tmp=tmp->next means that it is pointing to the next memory location which depends upon the compiler if the sizeof pointer is 4bytes it will move to 4 bytes.
精彩评论