为什么在链表中创建当前变量时不使用 "new"?
Why isn't "new" used while making the current variable in the linkedlist?
这是打印链表元素的解决方案。
为什么不是 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
会创建一个新的。
您不需要也不想创建一个新的。
您只想"use"一个指向现有节点的指针。
这只是将函数参数复制到具有不同名称的变量中。其实完全没有必要。
这是打印链表元素的解决方案。
为什么不是 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
会创建一个新的。
您不需要也不想创建一个新的。
您只想"use"一个指向现有节点的指针。
这只是将函数参数复制到具有不同名称的变量中。其实完全没有必要。