Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
struct node{
int data;
node* next;
};

What I have tried:

I know about nested structures when it comes to nesting a different structure but what confuses me is nesting the same structure.
Posted
Updated 18-Jul-19 23:19pm

 
Share this answer
 
next is a pointer to the next item in the list, as the name implies.

Think of each struct instance (each node) as a piece of paper. You have a dozen pieces of paper, and you write a different number between 1 and 12 in the top right corner - this is the "address" of the node.
Now put them in a stack on your desk, and take the topone. Write the data on it and write "Next: 0" at the bottom right.
You now have a list with one element - the 0 is the next address, and there aren't any.

Take another piece off your stack, write different data on it, put "Next: 0" in the bottom right, and then change the "0" on the previous sheet to the number in the top right of the new one.
You now have a list with two nodes: the first one holds the address of the second in the bottom right corner, and the second says "there are no more" with a zero in the bottom right.

As you add new sheets, you repeat the process, replacing the last sheet "0" with the address of the new sheet, until you have a full list - and you can track through the list from the first sheet just by following the "chain" of next pointers.

Give it a try on your desk, and you'll see what I mean.

That's what
C++
node* next;
means: next is a pointer to a node structure, and indicates the next item in the list.
 
Share this answer
 
C
struct node
{
  int data;
  node* next;
};
Such a code is typically used in linked list[^] implementation where a 'Node' contains some 'data' plus a pointer to the next 'Node':
 _______         ________
|       | next  |        | next
|data=5 | ----> |data=12 | ----> ...
|_______|       |________|
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900