【发布时间】:2021-03-22 13:39:01
【问题描述】:
这是显示来自 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;
}
【问题讨论】:
-
如果你不明白代码是如何工作的,你可以做的第一件事:用调试器单步调试。
标签: c++ data-structures linked-list