这是打印链表元素的解决方案。
为什么不是Node *current = new Node;
然后是current = head;
?
void printLinkedList(Node* head)
{
Node *current = head;
while(current!=NULL){
cout << current -> data << endl;
current = current -> next;
}
}
这是绘画的好地方!
想象一下,我们有一个由head
指向的链表:
head
|
v
+------+ +-----+ +-----+ +-----+
| i'm | -> | the | -> | bad | -> | guy | -> null
+------+ +-----+ +-----+ +-----+
如果使用代码行
Node *current = new Node;
然后,内存看起来像这样:
head current
| |
v v
+------+ +-----+ +-----+ +-----+ +------+
| i'm | -> | the | -> | bad | -> | guy | -> null | duh! | -> ?
+------+ +-----+ +-----+ +-----+ +------+
该函数的目标是打印由head
指向的现有列表,但是这里我们有一个指向不属于现有列表的新链接列表单元格的指针。结果,我们提交了两个编程罪:
另一方面,如果我们写
Node *current = head;
然后,内存看起来像这样:
head
|
v
+------+ +-----+ +-----+ +-----+
| i'm | -> | the | -> | bad | -> | guy | -> null
+------+ +-----+ +-----+ +-----+
^
|
current
[此处,current
现在指向现有列表,因此我们可以遍历列表以查找所需的内容。此处无需创建新节点,因此我们无需创建任何新节点。
通常来说,在C ++中,除非您确实要创建一个新的链表单元,否则应避免使用new
。在这种情况下,我们不想这样做,这就是为什么我们创建current
并将其指向现有的链接列表单元格的原因。
希望这会有所帮助!
因为该节点已经存在。
new
将创建一个新的。
您不需要或不想创建一个新的。
您只想“使用”指向现有节点的指针。
这里只是将函数参数复制到具有不同名称的变量中。实际上完全没有必要。