Wednesday, 20 August 2014

Filled Under:

C program to implement Singly Linked List

Share


Singly linked list is the most basic linked data structure. In this the elements can be placed anywhere in the heap memory unlike array which uses contiguous locations. Nodes in a linked list are linked together using a next field, which stores the address of the next node in the next field of the previous node i.e. each node of the list refers to its successor and the last node contains the NULL reference. It has a dynamic size, which can be determined only at run time.

Example of C program to implement Singly Linked List


#include<stdio.h>
#include<conio.h>
#include<alloc.h>
//-------------------------------------------------
struct node
{
int data;
struct node *next;
}*start=NULL;
//------------------------------------------------------------

void creat()
{
char ch;
 do
 {
  struct node *new_node,*current;

  new_node=(struct node *)malloc(sizeof(struct node));

  printf("nEnter the data : ");
  scanf("%d",&new_node->data);
  new_node->next=NULL;

  if(start==NULL)
  {
  start=new_node;
  current=new_node;
  }
  else
  {
  current->next=new_node;
  current=new_node;
  }

 printf("nDo you want to creat another : ");
 ch=getche();
 }while(ch!='n');
}
//------------------------------------------------------------------

void display()
{
struct node *new_node;
 printf("The Linked List : n");
 new_node=start;
 while(new_node!=NULL)
   {
   printf("%d--->",new_node->data);
   new_node=new_node->next;
   }
  printf("NULL");
}
//----------------------------------------------------
void main()
{
create();
display();
}
Output:
Enter the data : 10
Do you want to creat another :  y
Enter the data : 20
Do you want to creat another : y

Enter the data : 30
Do you want to creat another : n

The Linked List :
10--->20--->30--->NULL