sindhugauri sindhugauri - 2 months ago 15
C Question

Confusion regarding nodes in a Linked List

I have a question about Linked Lists. I spoke to a friend and am now confused.
Suppose that there are two variables of type struct node. One is ptr and the other is the header node.

struct node
{
int data;
struct node *link;
};
struct node *ptr,*header;


What is the difference between

ptr=header


and

ptr->link=header


and

ptr->link=header->link


?
Edit:I mean semantically.

Answer

Assuming header is pointing to an allocated node initially, it will look like

                       +----------------+-----------+
                       |                |           |
header  +----------->  |   data         |  link+-----------> other node/NULL
                       |                |           |
                       +----------------+-----------+

After ptr=header, both ptr and header points to the same node

                       +----------------+-----------+
pointer +----------->  |                |           |
header  +----------->  |   data         |  link+-----------> other node/NULL
                       |                |           |
                       +----------------+-----------+

After ptr->link=header,

                       +----------------+-----------+
pointer +----------->  |                |           |
header  +----------->  |   data         |  link+----------+ 
                +--->  |                |           |     |
                |      +----------------+-----------+     |
                +-----------------------------------------+  

after ptr->link=header->link, it would depend on where header and ptr are pointing

  • if they point to the same node then this statement will have no effect.
  • if they point to some different nodes then link pointer of both nodes pointed by ptr and header will point to the same node (or NULL).

                           +----------------+-----------+
                           |                |           |
    header  +----------->  |   data         |  link+--------------+                                                       |
                           |                |           |         |
                           +----------------+-----------+         +------> |
                                                                           |other node/NULL 
                                                                  +------> |
                           +----------------+-----------+         |
                           |                |           |         |
    ptr     +----------->  |   data         |  link+--------------+ 
                           |                |           |
                           +----------------+-----------+
    
Comments