将元素插入链接列表
Inserting Elements into a Linked-List
我正在阅读洛斯皮诺索的"C++速成课程",其中有以下代码。我不确定"new_element->下一个=下一个"这句话背后的原因。如果我删除它,代码仍然会产生相同的结果。
当"&trooper2"传递给insert_after方法时,trooper2的"next"指针是否指向trooper1的"next"指针指向的地方? 当它们都已经是空指针时,为什么要将 trooper2 的下一个指针分配给 trooper1 的下一个指针?
大家节日快乐,感谢您的帮助
#include <cstdio>
struct Element {
Element* next{};
void insert_after(Element* new_element) {
new_element->next = next;
next = new_element;
}
char prefix[2];
short operating_number;
};
int main() {
Element trooper1, trooper2, trooper3;
trooper1.prefix[0] = 'T';
trooper1.prefix[1] = 'K';
trooper1.operating_number = 421;
trooper1.insert_after(&trooper2);
trooper2.prefix[0] = 'F';
trooper2.prefix[1] = 'N';
trooper2.operating_number = 2187;
trooper2.insert_after(&trooper3);
trooper3.prefix[0] = 'L';
trooper3.prefix[1] = 'S';
trooper3.operating_number = 005;
for (Element* cursor = &trooper1; cursor; cursor = cursor->next) {
printf("Storm Trooper %c%c-%dn", cursor->prefix[0], cursor->prefix[1],
cursor->operating_number);
}
此代码的作用是在调用元素和它指向的元素之间插入一个元素。让我们看看发生了什么:
- 从骑兵1开始
= 士兵1> 空
- 在 trooper1 和 NULL 之间添加 trooper2
= 骑兵1>骑兵2>
空- 在 trooper2 和 NULL 之间添加 trooper3
= 骑兵1>骑兵2>骑兵3>
空您正在调用元素和下一个元素之间插入一个元素,该元素已经为 NULL。因此,您还将新元素设置为NULL 旁边。
**更新**
就像@Beta说的,如果你继续添加到第一个元素,你实际上会得到一个列表,其中新元素入到第二个位置。下一个元素是实际指向某物:
- 从骑兵1开始
= 士兵1> 空
- 在 trooper1 和 NULL 之间添加 trooper2
= 骑兵1>骑兵2>
空 在骑兵- 1 和骑兵 2 之间添加骑兵 3
= 骑兵1>骑兵3>骑兵2>
空 在骑兵- 1 和骑兵 3 之间添加骑兵 3
= 骑兵1>骑兵4>骑兵3>骑兵2>
空在此示例中,new_element->next = next;
没有区别,因为在执行函数之前(和之后(两个指针都是 null。但是如果你试试这个:
...
trooper1.insert_after(&trooper3);
...
trooper1.insert_after(&trooper2);
...
你会看到不同之处。使用该行,输出将与第一个示例中相同。没有这条线,trooper3
就会丢失。
相关文章:
- 从链接列表c++中删除一个项目
- 读取文件的最后一行并输入到链接列表时出错
- 下面是我为检测链接列表中的循环而制作的代码
- 有人能帮我处理这个链接列表吗?C++
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 链接列表运算符重载没有打印出我想要的内容
- 链接列表在 cpp 中包含不同的对象类
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 如何在构建链接列表时调整头、尾指针
- Shared_ptr双链接列表内存泄漏
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 在链接列表中查找元素 - C++
- 删除链接列表中剩余的最后一个节点
- 只有我的"链接列表"中的第一个节点正在打印
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 将元素插入链接列表