Thursday 9 August 2012

implementation of single linked list in c language


#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *link;
}NODE;
NODE *first=NULL,*last,*temp,*newnode;
void creation()
{
int ch;
do
{
newnode=(NODE*)malloc(sizeof(NODE));
newnode->link=NULL;
printf("\n enter the data of the node : ");
scanf("%d",&newnode->data);
if(first==NULL)
{
first=newnode;
}
else
{
last->link=newnode;
}
last=newnode;
printf("\n do u want to add one more node [1/0] : ");
scanf("%d",&ch);
}
while(ch==1);
}
void insertion()
{
int ch,data;
printf("\n 1.at first \n 2.at middle \n 3.at end ");
printf("\n enter your choice :");
scanf("%d",&ch);
newnode=(NODE *)malloc(sizeof(NODE));
newnode->link=NULL;
printf("\n enter the data for the new node :");
scanf("%d",&newnode->data);
switch(ch)
{
case 1:
newnode->link=first;
first=newnode;
break;
case 2:
printf("\n enter the data of the node after which you want to insert :");
scanf("%d",&data);
temp=first;
while(temp->data==data)
temp=temp->link;
newnode->link=temp->link;
temp->link=newnode;
break;
case 3:
temp=first;
while(temp->link!=NULL)
temp=temp->link;
temp->link=newnode;
last=newnode;
break;
default:
printf("\n invalid  choice ");
free(newnode);
}
}
void deletion()
{
int ch,data;
NODE *temp1;
if(first==NULL)
printf("\n list is empty ");
else
{
printf("\n1.first node \n2.middle node \n3.ending node ");
printf("\n enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
temp=first;
printf("\n deleted element is : %d ",first->data);
first=first->link;
free(temp);
break;
case 2:
printf("\n enter the data of the node that you want to delete : ");
scanf("%d",&data);
temp=first;
while(temp->link->data!=data)
temp=temp->link;
temp1=temp->link;
temp->link=temp->link->link;
free(temp1);
break;
case 3:
temp=first;
while(temp->link->link!=NULL)
temp=temp->link;
printf("\n deleted element is : %d ",temp->link->data);
temp1=temp->link;
temp->link=NULL;
free(temp1);
break;
default:
printf("\ninvalid choice");
}
}
}
void length()
{
int l=0;
temp=first;
while(temp!=NULL)
{
temp=temp->link;
l++;
}
printf("\n length of the list is : %d",l);
}
void display()
{
temp=first;
if(temp==NULL)
printf("\n list is empty...nothing to display ");
else
{
printf("\n");
while(temp!=NULL)
{
printf("%d-->",temp->data);
temp=temp->link;
}
}
}
void main()
{
int ch;
clrscr();
while(1)
{
printf("\n 1.creation \n 2.insertion \n 3.deletion \n 4.display \n 5.length");
printf("\n 6.exit \n Enter your choice :");
scanf("%d",&ch);
switch(ch)
{
case 1:
creation();
break;
case 2:
insertion();
break;
case 3:
deletion();
break;
case 4:
display();
break;
case 5:
length();
break;
case 6:
exit(0);
default:
printf("\ninvalid choice\n");
}
}
}

No comments:

Post a Comment