打印链接列表

时间:2012-08-19 11:07:49

标签: c linked-list

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

列表的基本结构。

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;
}

2 个答案:

答案 0 :(得分:3)

        temp = (list) malloc(sizeof(struct node));
        temp->num = i;
        head->next = temp;
        head->next = NULL;

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

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

答案 1 :(得分:3)

你不是在这里错过的东西:

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

您使用head覆盖了下一个NULL。您的第一个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 / head或类似名称。否则,可以轻松交换start和{{1}}的含义。

相关问题