struct node{ int data; node* next; }; Can someone explain intuitively what does "node* next" mean?
3 Answers
- 5 months ago
It means the next item in the structure which you are making. For example, if the structure you are coding is a List, then the next node is the next item in the list.
- husoskiLv 75 months ago
The statement "node *next;" declares a member variable in the struct named "next". The * before next means that next is a pointer, and "node" (or "struct node") is the data type that the variable will point to.
So this statement declares a member variable (named "next") that points to a node structure.
This is a very common pattern for declaring the "link" in a linked-list entry, as Quentin already noted.
A note on the syntax. This particular style of declaring variables is inherited from C. A declaration consists of a type, followed by a "declarator"; or possibly multiple declarators separated by commas. Each declarator is a name, and possibly some symbols to indicate more about the variable being declared.
int ivalue, *iptr, iarray[5], ifunc();
Bad style (don't group unrelated declarations like this), but that declares four variables: ivalue is an int; iptr is a pointer to an int, iarray is an array of ints, and ifunc is a function returning an int. The idea is that a variable is declared just as (or very nearly as) it will be used. A plain int variable is just a name. You get the value that iptr points to using the syntax *iptr, so the declarator is *iptr. You get a value from an array using [] brackets after the name, so you declare an array with [] brackets after the name. You call a function using () parentheses after then name, so you declare it that way.
(This doesn't apply to references, with a leading & in the declarator, but these were invented by Bjarne Stroustrup as part of C++ only, and Stroustrup is on record about not liking C declarators; referring to them as a "failed experiment." )
- ChrisLv 75 months ago
node* next declares a pointer.
It means that if you have a node instance called a, you can do
next = a;
The important thing here is to understand that this didn't create a copy of a!
The pointer "next" is now *pointing* at the node a, so if you were to print
next.data
you would actually get whatever is stored in a.data
And if you did
next.data = 4;
you'd actually change a.data to 4.
It also means that you can do something like
next.next.next.data
to get the data of a node two nodes further down the linked list.