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.
new_node->next = head;Thenextpointer of thenew_nodeis set to the pointer stored inhead. Now,new_node->next(andhead) point to the currently first node of your list.head = new_node;Now,headis overridden to point to the new node. No cycle in node pointers. From now on the new node is the head of your list.headis not an object,headis a pointer to an object. And it can be set to point to another object.