如何在链表的末尾添加元素 [英] How to add elements to the end of a linked list
问题描述
所以我试图在C ++中创建一个函数,应该在链表的末尾添加一个元素。
添加元素的函数应该在 main
-method中调用。
即使列表中没有元素,也应该可以调用它。
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...
推荐答案
尝试以下操作:
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;
}
这篇关于如何在链表的末尾添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!