0

So, I'm learning C++ and data structures. The first one I wanted to do was singly-linked lists. I created/copied the following code:

class Node {
public:
    int data;
    Node* next;
};

Node* head = NULL;

void createnode(int* value) {
    Node* new_node = new Node(); //allocate memory size of node
    new_node->data = *value; //data is given
    new_node->next = head;  //*next pointer is to head
    head = new_node;
}

void printlist(Node* n) {
    while (n != NULL) {
        cout << n->data << "\n";
        n = n->next;
    }
}

I'm struggling to visualise these two lines:

    new_node->next = head;  //*next pointer is to head
    head = new_node;

The 'next' node pointer, in the new node, is being set to 'head' of the linked list which is fine (I'm visualizing the node being inserted on the left side of 'head' and moving everything to the right, including this 'head' object). Then, in the next line, head is being set to 'new_node'.

So, it's created some sort of cyclical connection? Should the 'head' of this linked list not act as a sort of snake's head, with the values being added on behind, increasing the length of the snake, if you will.

10
  • 3
    So, it's created some sort of cyclical connection? No. You are just adding nodes at the front instead of the end. Commented Oct 26, 2020 at 15:10
  • The first one I wanted to do was singly-linked lists. I created/copied the following code Bad luck. This is not what I would call idiomatic C++ code... Commented Oct 26, 2020 at 15:10
  • 1
    new_node->next = head; The next pointer of the new_node is set to the pointer stored in head. Now, new_node->next (and head) point to the currently first node of your list. head = new_node; Now, head is overridden to point to the new node. No cycle in node pointers. From now on the new node is the head of your list. Commented Oct 26, 2020 at 15:15
  • 1
    To master the magic of pointers (and lists), try on paper (with pencil and eraser) where the nodes are boxes and the pointers are arrows. That's old-fashioned but somehow still effective... ;-) Commented Oct 26, 2020 at 15:17
  • 1
    head is not an object, head is a pointer to an object. And it can be set to point to another object. Commented Oct 26, 2020 at 15:27

1 Answer 1

1

Suppose you have a sequence:

  a -> b -> c -> NULL; // where head points to a

what those lines are doing is (suppose you want to add 'd' to the previous list):

 d -> a; // where a still points to wherever it used to point

and after that you update to where HEAD should point, which is no longer the node that had a, but the one that has d

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.