如何将元素添加到链接列表的末尾
How to add elements to the end of a linked list
所以我试图在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;
}
相关文章:
- 从链接列表c++中删除一个项目
- 读取文件的最后一行并输入到链接列表时出错
- 下面是我为检测链接列表中的循环而制作的代码
- 有人能帮我处理这个链接列表吗?C++
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 链接列表运算符重载没有打印出我想要的内容
- 链接列表在 cpp 中包含不同的对象类
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 如何在构建链接列表时调整头、尾指针
- Shared_ptr双链接列表内存泄漏
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 在链接列表中查找元素 - C++
- 删除链接列表中剩余的最后一个节点
- 只有我的"链接列表"中的第一个节点正在打印
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 将元素插入链接列表