chr*_*sik 0 c++ pointers linked-list list singly-linked-list
所以我试图在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;
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是它只是不起作用.我试过删除或添加参数 - 没什么帮助,我在互联网上找不到合适的答案.所以如果你们中的任何人都可以帮助我,我会非常非常高兴,因为我在这里绝望...
小智 5
仔细看看:
if (l == NULL)
{
l->digit = newDigit;
l->next = NULL;
}
Run Code Online (Sandbox Code Playgroud)
l == NULL .... l-> digit您正在取消引用NULL指针!
另一个问题是,你分配lh的ListElement *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;
}
}
Run Code Online (Sandbox Code Playgroud)