Akr*_*med 1 c++ pointers linked-list new-operator data-structures
这是打印链表元素的解决方案。
为什么不是Node *current = new Node;然后current = head;呢?
void printLinkedList(Node* head)
{
Node *current = head;
while(current!=NULL){
cout << current -> data << endl;
current = current -> next;
}
}
Run Code Online (Sandbox Code Playgroud)
这是画画的好地方!
想象一下,我们有一个指向的链表head:
head
|
v
+------+ +-----+ +-----+ +-----+
| i'm | -> | the | -> | bad | -> | guy | -> null
+------+ +-----+ +-----+ +-----+
Run Code Online (Sandbox Code Playgroud)
如果我们使用这行代码
Node *current = new Node;
Run Code Online (Sandbox Code Playgroud)
那么内存看起来像这样:
head current
| |
v v
+------+ +-----+ +-----+ +-----+ +------+
| i'm | -> | the | -> | bad | -> | guy | -> null | duh! | -> ?
+------+ +-----+ +-----+ +-----+ +------+
Run Code Online (Sandbox Code Playgroud)
该函数的目标是打印由 指向的现有列表head,但这里我们有一个指向不属于现有列表一部分的新链表单元格的指针。结果,我们犯了两个编程罪:
另一方面,如果我们写
Node *current = head;
Run Code Online (Sandbox Code Playgroud)
那么内存看起来像这样:
head
|
v
+------+ +-----+ +-----+ +-----+
| i'm | -> | the | -> | bad | -> | guy | -> null
+------+ +-----+ +-----+ +-----+
^
|
current
Run Code Online (Sandbox Code Playgroud)
在这里,current现在指向现有列表,因此我们可以遍历列表以找到我们需要的内容。这里不需要创建新节点,所以我们不创建任何新节点。
一般来说,在 C++ 中你应该避免使用,new除非你真的想创建一个新的链表单元。在这种情况下,我们不想这样做,这就是我们创建current并让它指向现有链表单元的原因。
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |