如何将元素添加到链接列表的末尾

 Genesis Gaming 发布于 2023-02-12 19:22

所以我试图在C++中创建一个函数,它应该在链表的末尾添加一个元素.应该在main-method中调用添加元素的函数.即使列表中没有元素,也应该可以调用它.

到目前为止我所拥有的是以下内容:

int main()
{
   ListElement* l = new ListElement;
   l->digit = 9;
   l->next = NULL;
   appendList(l, 5);
   appendList(l, 7);

   printList(l);

   return 0;
}

void appendList(ListElement *&l, int newDigit)
{
    ListElement *lh = new ListElement;

    if(l == NULL)
    {
        l->digit = newDigit;
        l->next = NULL;
    }
    else
    {
        lh=l;

        while(lh != NULL)
        {
           lh=lh->next;
        }
        lh=lh->next;
        lh->digit = newDigit;
        lh->next = NULL;
        l = lh;
    }
}

不幸的是它只是不起作用.我试过删除或添加参数 - 没什么帮助,我在互联网上找不到合适的答案.所以如果你们中的任何人都可以帮助我,我会非常非常高兴,因为我在这里绝望...

1 个回答
  • 仔细看看:

    if (l == NULL)
    {
        l->digit = newDigit;
        l->next = NULL;
    }
    

    l == NULL .... l-> digit您正在取消引用NULL指针!

    另一个问题是,你分配lhListElement *lh = new ListElement;,然后立即用覆盖其价值l在"其他"块lh=l;.

    尝试这样的事情:

    #include <cassert>
    #include <iostream>
    
    struct ListElement final {
        explicit ListElement(int digit) : digit{digit} {}
    
        int digit = 0;
        ListElement* next = nullptr;
    };
    
    void appendList(ListElement*& l, int newDigit);
    void printList(ListElement* l);
    void freeList(ListElement* l);
    
    int main() {
        ListElement* l{nullptr};
        appendList(l, 9);
        appendList(l, 5);
        appendList(l, 7);
        printList(l);
        freeList(l);
    }
    
    void appendList(ListElement*& l, int newDigit) {
        if (!l) {
            // Creating first element of the list.
            l = new ListElement{newDigit};
            return;
        }
    
        // Since we got a single linked list and don't have a pointer
        // to its tail, iterate over the list to get the last element
        // to append to...
        auto tail = l;
        while (tail->next)
            tail = tail->next;
        assert(tail->next == nullptr);
        tail->next = new ListElement{newDigit};
    }
    
    void printList(ListElement* l) {
        unsigned int index = 0;
        while (l != nullptr) {
            std::cout << index++ << ": " << l->digit << '\n';
            l = l->next;
        }
    }
    
    void freeList(ListElement* l) {
        ListElement* tmp;
        while (l != nullptr) {
            tmp = l;
            l = l->next;
            delete tmp;
        }
    }
    

    2023-02-12 19:23 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有