Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node *next in linked list

I am a newbie in data-structures and algorithms. I came across the following code

typedef struct node                                                
    {                                                               
          int data;            
          node *next;            
    };               

Can anyone please tell me why are we declaring node *next? Can't *next be declared as int *next?

like image 355
curious_coder Avatar asked Apr 22 '26 05:04

curious_coder


1 Answers

Because you'll want to be able to do n->next->next->next... and so on.

next needs to point to another node, not an int, else you won't be able to see the next int after that (you cannot do (aInt)->next, can you?)!

You can see nodes as small boxes that contain a int (or any other data) and a reference to the next little box. If you point directly to the data, you won't be able to get the box after that (it's just dumb data!) - you need to point to boxes (nodes)!

Here's an image that might help to see what I mean (credits goes to Virginia Tech): Here's a little image explaining it

like image 50
mbinette Avatar answered Apr 24 '26 20:04

mbinette



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!