Rimantas Radžiūnas
Rimantas Radžiūnas

Reputation: 257

Using structures for singly linked lists

I've been wondering:

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

I believe the *head variable is the first pointer of linked list, but why is it written outside of structure brackets? Why I need to write it outside of whole structure? Could anyone answer, because I'm abit lost in whole linked list thing. And why do we need to declare *next pointer with "struct node" if it is already in whole "node" structure?

Upvotes: 0

Views: 61

Answers (1)

Paul92
Paul92

Reputation: 9062

head is just a pointer of type struct node*. An equivalent declaration is:

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

Note that even if you don't declare any variable of the type of the structure you're defining, you must put a semicolon after the closing curly brace.

The origin of this syntax is that the struct is a data type and the way you declare variables is by specifying their data type and their name. Indeed, you can do this:

struct {int a, b;} *variable;

Upvotes: 5

Related Questions