【问题标题】:Printing the linked list打印链表
【发布时间】:2012-08-15 02:17:24
【问题描述】:

由于某种原因,我无法打印整个链表。我哪里会出错? 请帮忙。提前致谢。

列表的基本结构。

struct node
{
    int num;
    struct node *next;
};

typedef struct node *list;

主要功能。

int main()
{
    int i, j, k, l;
    list head = NULL, start = NULL, temp, p;

    printf("Enter the number of nodes in the list: ");
    scanf("%d", &k);

链表的形成。

    for(i=0;i<k;i++)
    {
        if (i==0)
        {
            start = (list) malloc(sizeof(struct node));
            start->num = i;
            head = start;
            head->next = NULL;
        }
        else
        {   
            temp = (list) malloc(sizeof(struct node));
            temp->num = i;
            head->next = temp;
            head->next = NULL;
        }
    }   

打印链表。

    p = start;
    while(p != NULL)
    {
        printf("%d", p->num);
        p = p->next;
    }
    return 0;
}

【问题讨论】:

    标签: c linked-list


    【解决方案1】:

    你是不是错过了什么:

    head->next = temp;
    head->next = NULL;
    

    您正在用NULL 覆盖您的下一个head。您应该首先将您的head 指向temp

    head->next = temp;   // (4) see my comment on this post for 
    head = temp;         // (5) the meaning of the number
    head->next = NULL;   // (6)
    

    编辑:顺便说一句,您应该将 head 重命名为 current/last 或类似的名称。否则,headstart 的含义很容易互换。

    【讨论】:

    • 第二个元素不会被这个大小列表的建议覆盖 >=3 吗?
    • 没有?不要不必要地混淆我>.
    • 这是一个问题 - 我自己也不确定:| - 原来的head-&gt;next 似乎没有保存并将被丢弃,但正如我所说 - 我不确定,因此是这个问题。
    • 正如我所见,在启动范围时,(1)head 已经正确初始化。 (2)然后temp的其他字段正在初始化(int)。由于head 指向我们的最后一个项目,(3) 我们将让他的nextpointer 指向我们的新项目。现在我们的最后一项已完全初始化,我们不再需要指向它的指针,(4)因此我们可以将新项设为新的head。 (5) 新的head 当然指向NULL,我们的head 将按照(1)中的要求正确初始化。
    • 好的,我现在看到了。您的建议中的head 实际上指向最后一个元素,因此它应该可以正常工作。我无法正确遵循它 - 因此我问了。这 - 除了您关于重命名的编辑之外值得 +1。
    【解决方案2】:
            temp = (list) malloc(sizeof(struct node));
            temp->num = i;
            head->next = temp;
            head->next = NULL;
    

    您始终将新元素放置为第二个元素,然后将其删除 - 有效地使您的列表大小恒定为 1。

    您可能需要设置temp-&gt;next = NULL(而不是head-&gt;next设置element-&gt;next = temp - 其中element 是列表中的最后一个元素(而不是head) .
    (另一种方法是将元素添加为新的head,并设置temp-&gt;next = head;

    【讨论】:

    • 我知道我哪里出错了。感谢回复。 :)
    猜你喜欢
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 2016-06-15
    • 2012-10-25
    • 1970-01-01
    相关资源
    最近更新 更多