插入链表出错

Inserting in Linked List goes wrong

我不知道我的代码有什么问题。我有使用链表的经验,但今天我不知道出了什么问题。

当我想使用 printNodes() 函数打印链表时,它不会打印前两个节点。我插入的方式不对,但不知道哪里出错了。

struct node *makeNode(int data)
{
    struct node *temp = (struct node *)malloc(sizeof(struct node) * 1);
    temp->data = data;
    temp->next = NULL;
    return temp;
}

struct node *insertEnd(int data, struct node *head)
{
    struct node *temp = makeNode(data);
    if (head == NULL)
    {
        return temp;
    }

    struct node *loop = head;
    while (loop->next)
    {
        loop = loop->next;
    }
    loop->next = temp;
}

void printNodes(struct node *head)
{

    struct node *loop = head;
    while (loop)
    {
        printf("%d ", loop->data);
        loop = loop->next;
    }
}

int main()
{
    struct node *head = NULL;
    head = insertEnd(5, head);
    head = insertEnd(10, head);
    head = insertEnd(15, head);
    head = insertEnd(20, head);

    printNodes(head);
    printf("%d", head->data); <-- The data inside the head node doesn't get printed
}

您的 insertEnd 缺少针对一般情况的 return 语句。

insertEnd的最后添加以下内容:

return head;
struct node *insertEnd(int data, struct node *head)
{
    struct node *temp = makeNode(data);
    if (head == NULL)
    {
        return temp;
    }

    struct node *loop = head;
    while (loop->next)
    {
        loop = loop->next;
    }
    loop->next = temp;
    return head; //I think you missed this in your implementation
}

或者,您始终可以在开头添加项目,然后反向打印列表。正如@maraca 在评论部分提到的那样。请访问 here 查看在链表中插入节点的不同方法。