C中的链表语法

时间:2016-03-13 23:58:54

标签: c linked-list

我试图通过图表可视化来理解链表的语法。但是我很困惑。此代码打印出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("%d\n",start->item);
        start = start->link;
    }
    return 0;
} 

1 个答案:

答案 0 :(得分: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("%d\n", list->item);
        list = list->link;
    }
    return 0;
}

将其与以下内容进行比较,希望这些目标/意图更清晰:

*if((this.balance - out) !>= 0.0)*