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

How to add elements to the end of a linked list

本文关键字:列表 链接 元素 添加      更新时间:2023-10-16

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

到目前为止,我有以下内容:

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

不幸的是,它根本不起作用。我试过删除或添加参数,但没有任何帮助,我在互联网上找不到合适的答案。所以,如果你们中的任何人能帮助我,我会非常非常高兴,因为我在这里有点绝望。。。

仔细查看:

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

l=NULLl->数字您正在取消引用NULL指针!

另一个问题是在ListElement *lh = new ListElement;中分配lh,然后在"else"块lh=l;中立即用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;
    }
}

尝试以下

void appendList( ListElement * &head, int newDigit )
{
    if ( head == 0 )
    {
        head = new ListElement;
        head->digit = newDigit;
        head->next  = 0;
    }
    else
    {
        ListElement *next = head;
        while ( next->next ) next = next->next;
        next->next = new ListElement;
        next->next->digit = newDigit;
        next->next->next  = 0;
    }
} 

int main()
{
    ListElement *head = 0;
    appendList( head, 9 );
    appendList( head, 5 );
    appendList( head, 7 );
    printList( head );
    return 0;
}