Search code examples
c++pointersdata-structureslinked-listnew-operator

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


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;
    }
}

Solution

  • 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!