问题
So I am trying to create a function in C++ that should add an element at the end of an linked list.
This function that adds the elements should be called within the main
-method.
It should be possible to call it even if there is no element in the list.
What I have so far is the following:
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;
}
}
Unfortunately it just isn't working. I've tried removing or adding parameters - nothing helped and I couldn't find an appropriate answer on the internet. So if anyone of you could help me, I'd be very, very happy because I'm kind of despairing here...
回答1:
Try the following
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;
}
回答2:
Look closely at:
if (l == NULL)
{
l->digit = newDigit;
l->next = NULL;
}
l == NULL .... l->digit You are dereferencing a NULL pointer!
Another problem is that you allocate lh
in ListElement *lh = new ListElement;
and then immediately overwrite its value with l
in "else" block lh=l;
.
Try something like this instead:
#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;
}
}
来源:https://stackoverflow.com/questions/20384407/how-to-add-elements-to-the-end-of-a-linked-list