这是udemy教程中显示链表的代码,这里我们将使用一个数组并将这些值存储在链表中。我不明白代码是怎么工作的。在下面的代码中,我们存储下一个节点的地址,如何last->next=temp;在我没有创建last=new node这样的最后一个节点的地方工作;我只创建了最后一个指针。我没弄明白,有人能给我解释一下它是怎么工作的吗
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
};
int main() {
int A[] = {3, 5, 7, 10, 15};
Node* head = new Node;
Node* temp;
Node* last;
head->data = A[0];
head->next = nullptr;
last = head;
// Create a Linked List
for (int i=1; i<sizeof(A)/sizeof(A[0]); i++){
// Create a temporary Node
temp = new Node;
// Populate temporary Node
temp->data = A[i];
temp->next = nullptr;
// last's next is pointing to temp
last->next = temp;
last = temp;
}
// Display Linked List
Node* p = head;
while (p != nullptr){
cout << p->data << " -> " << flush;
p = p->next;
}
return 0;
}
计算指针的最好方法是用笔(笔)和纸画方框和箭头。
下面是一个(悲伤的)ASCII版本,它描述了所发生的事情:
head->data = A[0];
head->next = nullptr;
last = head;
head
指向新创建的节点,last
指向与head
相同的位置:
head
|
v
+------+------+
| data | next |
| |(null)|
| | |
+------+------+
^
|
last
接下来,
// Create a temporary Node
temp = new Node;
// Populate temporary Node
temp->data = A[i];
temp->next = nullptr;
看起来是这样的:
head temp
| |
v v
+------+------+ +------+------+
| data | next | | data | next |
| |(null)| | |(null)|
| | | | | |
+------+------+ +------+------+
^
|
last
然后
last->next = temp;
将last
节点的next
成员更改为(在第一次迭代中,此节点与head
指向的节点相同):
head temp
| |
v v
+------+------+ +------+------+
| data | next | | data | next |
| | ---------->| |(null)|
| | | | | |
+------+------+ +------+------+
^
|
last
最后,使last
指向最近创建的节点:
last = temp;
这给出了
head temp
| |
v v
+------+------+ +------+------+
| data | next | | data | next |
| | ---------->| |(null)|
| | | | | |
+------+------+ +------+------+
^
|
last
然后从那里重复循环。
您已经在for循环之前使用last=head
将变量last初始化为head。这样做是为了确保在向列表中添加其他节点时不会修改原始头。在每次迭代中,使用最后一个节点来跟踪链表中的最后一个节点,以便将每个新节点添加到链表的末尾。