I wonder, what is the difference between:
struct Node
{
int data;
Node *next;
};
and
struct Node
{
int data;
struct Node *next;
};
Why do we need struct keyword in second example?
Also, what is the difference between
void Foo(Node* head)
{
Node* cur = head;
//....
}
and
void Foo(struct Node* head)
{
struct Node* cur = head;
//....
}
Only the declarations including struct are valid in C. There is no difference in C++.
However, you can typedef the struct in C, so you don’t have to write it every time.
typedef struct Node
{
int data;
struct Node *next; // we have not finished the typedef yet
} SNode;
SNode* cur = head; // OK to refer the typedef here
This syntax is also valid in C++ for compatibility.
Struct node is a new user defined datatype that we create. And unlike classes the new data type using structures is "struct strct_name" , ie; u need the keyword struct in front of the struct_name. For classes u do not need keywords in front of the new data type name. eg;
class abc
{
abc *next;
};
and when u declare variables
abc x;
instead of struct
abc x;
in case of structures . Also understand that by the statement
struct node * next;
we are trying to create a pointer that points to a variable of type "strcut node", which is called a self referential pointer in this case since it points to the parent structure.