为什么不是“新的"?使链表中的当前变量时使用? [英] Why isn't "new" used while making the current variable in the linkedlist?

查看:68
本文介绍了为什么不是“新的"?使链表中的当前变量时使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is the solution to printing elements of a linked list.

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

void printLinkedList(Node* head)
{
    Node *current = head;    
    while(current!=NULL){
        cout << current -> data << endl;
        current = current -> next;
    }
}

推荐答案

这是绘制图片的好地方!

This is a great spot to draw pictures!

想象一下,我们有一个由head指向的链接列表:

Imagine we have a linked list pointed at by head:

 head
   |
   v
+------+    +-----+    +-----+    +-----+
| i'm  | -> | the | -> | bad | -> | guy | -> null
+------+    +-----+    +-----+    +-----+

如果我们使用代码行

Node *current = new Node;

然后内存看起来像这样:

then memory looks like this:

 head                                                current
   |                                                    |
   v                                                    v
+------+    +-----+    +-----+    +-----+            +------+
| i'm  | -> | the | -> | bad | -> | guy | -> null    | duh! | -> ?
+------+    +-----+    +-----+    +-----+            +------+

该函数的目标是打印由head指向的现有列表,但是这里我们有一个指向不属于现有列表的新链接列表单元格的指针.结果,我们犯了两个编程罪:

The goal of the function is to print the existing list pointed at by head, but here we've got a pointer to a new linked list cell that isn't a part of the existing list. As a result, we've committed two Programming Sins:

  • 我们已经为不需要的对象分配了内存.
  • 我们违反了与客户签订的合同.

另一方面,如果我们写

Node *current = head;

然后内存看起来像这样:

then memory looks like this:

 head
   |
   v
+------+    +-----+    +-----+    +-----+
| i'm  | -> | the | -> | bad | -> | guy | -> null
+------+    +-----+    +-----+    +-----+
   ^
   |
current

在这里,current现在指向现有列表,因此我们可以遍历该列表以找到所需的内容.这里不需要创建新节点,因此我们无需创建任何新节点.

Here, current is now pointing into the existing list, so we can walk the list to find what we need. No new nodes need to be created here, so we don't create any new nodes.

通常来说,在C ++中,除非您真正想创建一个新的链表单元格,否则应避免使用new.在这种情况下,我们不想这样做,这就是为什么我们创建current并将其指向现有的链接列表单元格的原因.

Generally speaking, in C++ you should avoid using new unless you really truly want to create a new linked list cell. In this case, we don't want to do that, which is why we create current and have it point to an existing linked list cell.

希望这会有所帮助!

这篇关于为什么不是“新的"?使链表中的当前变量时使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆