将元素插入链接列表

Inserting Elements into a Linked-List

本文关键字:列表 链接 插入 元素      更新时间:2023-10-16

我正在阅读洛斯皮诺索的"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就会丢失。