为什么在链接列表中创建当前变量时不使用“新的”?

问题描述 投票:1回答:2

这是打印链表元素的解决方案。

为什么不是Node *current = new Node;然后是current = head;

void printLinkedList(Node* head)
{
    Node *current = head;    
    while(current!=NULL){
        cout << current -> data << endl;
        current = current -> next;
    }
}
c++ pointers data-structures linked-list new-operator
2个回答
2
投票

这是绘画的好地方!

想象一下,我们有一个由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并将其指向现有的链接列表单元格的原因。

希望这会有所帮助!


0
投票

因为该节点已经存在。

new将创建一个新的。

您不需要或不想创建一个新的。

您只想“使用”指向现有节点的指针。

这里只是将函数参数复制到具有不同名称的变量中。实际上完全没有必要。

© www.soinside.com 2019 - 2024. All rights reserved.