【问题标题】:Inserting in Linked List goes wrong插入链表出错
【发布时间】:2021-11-03 11:35:14
【问题描述】:

我无法弄清楚我的代码有什么问题。我有使用链接列表的经验,但今天我不知道出了什么问题。

当我想使用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 如果 head 不为空,则不会返回任何内容。此外,最好有头和尾,这样您就不必每次在最后添加一些东西时都迭代整个列表。
  • 或者,您可以始终在开头添加项目,然后反向打印列表。
  • 永远不要这样,谢谢!

标签: c list algorithm structure


【解决方案1】:

您的insertEnd 缺少用于一般情况的return 语句。

insertEnd的最后添加以下内容:

return head;

【讨论】:

    【解决方案2】:
    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查看在链表中插入节点的不同方式。

    【讨论】:

    • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 2020-10-13
    • 2017-08-27
    • 2013-02-28
    • 2016-06-04
    • 1970-01-01
    相关资源
    最近更新 更多