Dee Khan
Dee Khan

Reputation: 83

confusion in basics of linklist

I was going through the linked list and I have confusion. maybe I am mixing the concept or something else. Here is the code of creating the header node.

struct node
{
   int data;
   struct node *link;
};
node *head;
void main()
{
   head = new node;
}

1)The first thing I want to know is how can we write struct node *link; in inside the same node structure? because using first the node structure is created then we can declare pointer of that.
2) node *head; will already declare a memory of size node, then we need to do again head = new node;?

Upvotes: 3

Views: 62

Answers (2)

Brian
Brian

Reputation: 339

A link list is a chain of objects. What you are doing here is creating a struct with two variables. One is the date to store in this node. The other is a recursive struct. This where link lists get their name. One struct links to the next. When this node is created, link has no value but you can add nodes by creating a new node and storing it in link.

As for the rest of your code, I don't think you are doing it right. Usually nodes are wrapped in a link list class so that you can control the link list by adding, deleting and searching the nodes. When you are controlling a link list you need at least two pointers. One to point to the first node in the list (also called the "head"). The second pointer is the search pointer that will start at the head and go node by node until you find what you are looking for.

Now to answer your second question when you write node* head you are only declaring the pointer. You are not declaring "a memory of size node" so in the initialize function of the link list you need to create the first node and have the head point to it head = new node;

Upvotes: 0

dlmeetei
dlmeetei

Reputation: 10391

The self referential struct can hold a pointer to itself. Please do not confuse with size of pointer to size of structure. Size of pointer is constant irrespective of data type.

struct node
{
    int data;
    struct node *link;
};

Had it the struct node *link be something else like struct node link, It will not compile just like you think.

regarding why allocation by using the new is required, when we do node *head, it says that head points to memory location of actual node with area for data and link.

It might be useful to read pointer concept again

Upvotes: 1

Related Questions