我试图通过图表可视化来理解链表的语法。然而,我感到困惑。此代码打印出 0-9。我不明白评论的位,请直观地解释一下。
#include <stdio.h>
#include <stdlib.h>
struct node
{
int item;
struct node* link;
};
int main()
{
struct node *start,*list;
int i;
start = (struct node *)malloc(sizeof(struct node)); //???????
list = start; // ????????
start->link = NULL; // ??????????
for(i=0;i<10;i++)
{
list->item = i;
list->link = (struct node *)malloc(sizeof(struct node));
list = list->link;
}
list->link = NULL; //????????????
while(start != NULL) //??????????????
{
printf("%dn",start->item);
start = start->link;
}
return 0;
}
int main()
{
struct node *start,*list;
int i;
// Allocate memory for a single node
start = (struct node *)malloc(sizeof(struct node)); //???????
// The head of the list is starting node.
// (This head represented by `list` will be advanced when building;
// while the head represented by `start` will not be advanced
// until iterating for display.)
list = start; // ????????
// The starting node has no 'next' yet.
// (This is not technically needed in this exact code.
// The code would have been more clear with the assignment of
// null to the 'next' after each malloc to start with a clean node.)
start->link = NULL; // ??????????
for(i = 0; i < 10; i++)
{
list->item = i;
list->link = (struct node *)malloc(sizeof(struct node));
list = list->link; // Move to the next (newly created) node.
}
// The last node has no 'next' node. Need to manually assign it
// a value because it "could be anything" until properly initialized.
// (Intermediate nodes have had the 'next' assigned in the loop.)
list->link = NULL; //????????????
// Iterate over the list, using `start` to track the head and
// keep iterating until the end of the list is reached.
while(start != NULL) //??????????????
{
printf("%dn",start->item);
start = start->link; // Move to the 'next' node
}
return 0;
}
将其与以下内容进行比较,希望可以使目标/意图更加明确:
struct node *create_node(int value) {
struct node *n = malloc(sizeof(struct node));
n->item = value; // all nodes start with some value
n->link = NULL; // all nodes start without a 'next'
return n;
}
int main()
{
struct node *start,*list;
int i;
// Create list of elements 0..9
// (Creating the start node first avoids a condition check;
// pulling out the value assignment from the subsequent/trailing loop
// is for clarity.)
start = create_node(0);
list = start;
for(i = 1; i < 10; i++) // Changed loop count - value assigned in create
{
list->link = create_node(i);
list = list->link;
}
// Display - note reset of tracked head to beginning of list
list = start;
while(list != NULL)
{
printf("%dn", list->item);
list = list->link;
}
return 0;
}