Why isn't “new” used while making the current variable in the linkedlist?

我是研究僧i 提交于 2020-05-31 04:49:21

问题


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

Why isn't it Node *current = new Node; and then current = head;?

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

回答1:


This is a great spot to draw pictures!

Imagine we have a linked list pointed at by head:

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

If we use the line of code

Node *current = new Node;

then memory looks like this:

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

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:

  • We've allocated memory for an object we don't need.
  • We've broken the contract we made with the client.

On the other hand, if we write

Node *current = head;

then memory looks like this:

 head
   |
   v
+------+    +-----+    +-----+    +-----+
| i'm  | -> | the | -> | bad | -> | guy | -> null
+------+    +-----+    +-----+    +-----+
   ^
   |
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.

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.

Hope this helps!




回答2:


Because the node already exists.

new would create a new one.

You don't need or want to create a new one.

You just want to "use" a pointer to an existing node.

Here's it's just the function argument being copied into a variable with a different name. It's actually completely unnecessary.



来源:https://stackoverflow.com/questions/61086487/why-isnt-new-used-while-making-the-current-variable-in-the-linkedlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!