curious_coder
curious_coder

Reputation: 2468

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?

Upvotes: 2

Views: 11146

Answers (2)

mbinette
mbinette

Reputation: 5094

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

Upvotes: 14

Swapnil
Swapnil

Reputation: 8318

You can, but it won't help you write a linked list. node *next ensures that you've a variable next which is a pointer to the node. int *next would mean that next would point to an integer and not the node, won't give you the linked list, which is what you seem to be looking for.

Upvotes: 1

Related Questions