Advertisment

More on linked lists

author-image
CIOL Bureau
Updated On
New Update

As already mentioned in the previous tutorial, a linked list consists of

several nodes where each node contains two fields, one containing the item and

the other containing the address of the next item which is in the form of a

pointer. Let’s take a look at one such node:



struct node


{


int item;


struct node *next;


};



Advertisment

The first member is an integer item and the second a pointer to the next node

in the list as shown below. In this example, we’ve only considered one element

item in the structure for simplicity but you could have any number of elements

of any complex datatype. The pointer next is of the same structure type in which

it is a member, such structures that contain a member field that point to the

same structure type are called self-referential structures.



Let’s illustrate the concept of linked lists by linking two nodes. Consider a
structure



struct link


{


int num;


char name<20>;


float age;


struct link *next;


};


struct link node1, node2;







This creates two nodes of type struct link that are independent of each

other. Now to link them, we need to make node1 point to node2. This can be done

if the pointer next of node1 is made to hold the address of node2.



node1.next = &node2

Assigning values to the other fields is done in the usual manner.



node1.num = 1;


node1.name = "Ram";


………..


node2.num = 2;


………..


So we now have a list containing two nodes and any number of nodes can be
created in a similar manner. For example,



node2.next = &node3





would add another link provided node3 has been declared as a variable of type

struct link.



Now, let’s say we’ve created a linked list containing ten nodes, the pointer
next of the last node in the list is assigned the value null to indicate the end

of the list.



node10.next = 0;

tech-news