A linked list is a sequence of data structures, which are connected together via links. Linked List is a sequence of links which contains items. Each link contains a connection to another link. Linked list is the second most-used data structure after array. Following are the important terms to understand the concept of Linked List.
A linked list is a way to store a collection of elements. Like an array these can be character or integers. Each element in a linked list is stored in the form of a node.
A node is a collection of two sub-elements or parts. A data part that stores the element and a next part that stores the link to the next node.
A linked list is formed when many such nodes are linked together to form a chain. Each node points to the next node present in the order. The first node is always used as a reference to traverse the list and is called HEAD. The last node points to NULL.
In C language, a linked list can be implemented using structure and pointers .
typedef struct mynode{ int data; struct mynode *link; }Node;
Node *ptr;//Define Node as pointer of data type struct mynode
typedef is used to define a data type in C. malloc() is used to dynamically allocate a single block of memory in C, it is available in the header file stdlib.h. sizeof() is used to determine size in bytes of an element in C. Here it is used to determine size of each node and sent as a parameter to malloc.
/* Write a program in C to implement Singly linked list */
#include<stdio.h>
#include<stdlib.h>
typedef struct mynode
{
int info;
struct mynode *link;
}Node;
Node *start=NULL;
void add_node(int);
void display();
int main()
{
int value,count=0;
char choice;
while(1)
{
printf("\n Do you wish to insert the node(y/n)?");
scanf("%c",&choice);
__fpurge(stdin);// for Windows OS use fflush(stdin)
if(choice=='Y'||choice=='y')
{
printf("\n Enter the info of Node:");
scanf("%d",&value);
add_node(value);
__fpurge(stdin);// for Windows OS use fflush(stdin)
}
else
{
break;
}
}
printf("\n The Linked List is:\n\n");
display();
return 0;
}
void add_node(int data)
{
Node *newptr=NULL;
Node *ptr;
newptr=(Node*)malloc(sizeof(Node));
newptr->info=data;
newptr->link=NULL;
if(start==NULL)
{
start=newptr;
}
else
{
ptr=start;
while(ptr->link!=NULL)
{
ptr=ptr->link;
}
ptr->link=newptr;
}
}
void display()
{
Node *ptr=start;
printf("->");
while(ptr)
{
printf("%d->",ptr->info);
ptr=ptr->link;
}
printf("NULL\n");
} /* End of the Program */
Comments