I have a good amount of experience with Java, but am an absolute beginner in C . In C , a node for a linked list would include:
class Node {
int data;
Node *next
Node(int d) {
data = d;
*next = NULL;
}
}
Why a pointer to next and not for data?
CodePudding user response:
Why a pointer to next
Because you cannot have a node inside a node. If a node contains a node, then the inner node also contains a node, and that node contains a node, and that node contains a node, and that node contains a node, and that node contains a node, and that node contains a node, and that node contains a node ...
Can you spot the problem? It's impossible for a type to contain another object of its own type. Linked data structures work by pointing to nodes.
not for data?
Because you don't need a pointer for the data if you store the data within the node.
To programmers who come from Java, it may be useful to understand that all variables of class types are actually pointers in Java.
CodePudding user response:
It's because you don't need data to be a pointer. If it is a pointer then you need to make another variable, actually containing the data(which is pointless), where "Node *next" points to the adress, containing the next element of type class Node.
CodePudding user response:
Why a pointer to next and not for data?
By storing a pointer to the data in the next node, you won't be able to access the node next to the next node, (i.e. you can't get the node to which some data belongs to by just having a pointer to the stored data, you need to have a pointer to the node itself, which you can dereference to get the data it is pointing to).