Friday, January 9, 2015

Linked List Basic Operation in C

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<stdlib.h>
struct link
{
int no;
struct link *next;
};
typedef struct link node;
void create();
void firstinsert();
void lastinsert();
void middleinsert();
void firstdelete();
void middledelete();
void lastdelete();
void display();

node *start=NULL,*ptr=NULL;

void main()
{
int ch;
char choice;
clrscr();
do
{
printf("\n\n\t\t Linked List\n");
printf("1.Create\n");
printf("2.First Insert\n");
printf("3.Middle Insert\n");
printf("4.Last Insert\n");
printf("5.First Delete\n");
printf("6.Middle Delete\n");
printf("7.Last Delete\n");
printf("8.Display\n");

printf("Enter your choice-->");
scanf("%d",&ch);

switch(ch)
{
case 1:
create();
break;
case 2:
firstinsert();
break;
case 3:
middleinsert();
break;
case 4:
lastinsert();
break;
case 5:
firstdelete();
break;
case 6:
middledelete();
break;
case 7:
lastdelete();
break;
case 8:
display();
break;
case 9:
exit(0);
default:
printf("Sorry Wrong Choice....!!!\n");
}
printf("Do you want to continue....::");
fflush(stdin);
scanf("%c",&choice);
}while(choice=='y' || choice=='Y');
}
void create()
{
int i;
for(i=0;i<5;i++)
{
if(start==NULL)
{
start=(node *)malloc(sizeof(node));
ptr=start;
}
else
{
ptr->next=(node *)malloc(sizeof(node));
ptr=ptr->next;
}
printf("Enter value-->");
scanf("%d",&ptr->no);
}
ptr->next=NULL;
}
void firstinsert()
{
node *new1;
new1=(node *)malloc(sizeof(node));

printf("Enter a value to insert-->>");
scanf("%d",&new1->no);

new1->next=start;
start=new1;
}
void middleinsert()
{
node *new1,*ptr1;
int i,location;
ptr1=start;

printf("Enter the location at which you want to insert-->>");
scanf("%d",&location);

new1=(node *)malloc(sizeof(node));

printf("Enter a value to insert-->>");
scanf("%d",&new1->no);

if(location==1)
{
new1->next=start;
start=new1;
}
else
{
for(i=1;i<(location-1);i++)
{
ptr1=ptr1->next;
}
new1->next=ptr1->next;
ptr1->next=new1;

}
}
void lastinsert()
{
if(start==NULL && ptr==NULL)
{
start=(node *)malloc(sizeof(node));
ptr=start;
}
else
{
ptr->next=(node *)malloc(sizeof(node));
ptr=ptr->next;
}
printf("Enter a value to insert-->>");
scanf("%d",&ptr->no);
ptr->next=NULL;
}
void firstdelete()
{
node *temp,*ptr1;
ptr1=start;
if(start->next==NULL)
{
free(start);
start=NULL;
}
else
{
temp=start;
start=ptr1->next;
free(temp);
}
}
void middledelete()
{
node *temp;
int i,location;
ptr=start;

printf("Enter the location at which you want to delete-->>");
scanf("%d",&location);

for(i=1;i<location-1;i++)
{
ptr=ptr->next;
}
temp=ptr->next;
ptr->next=ptr->next->next;
free(temp);
}
void lastdelete()
{
node *ptr1,*temp;
ptr1=start;

while(ptr1->next->next!=NULL)
{
ptr1=ptr1->next;
}
temp=ptr1->next;
ptr1->next=NULL;
free(temp);

}
void display()
{
node *ptr1;
ptr1=start;

printf("\n\nDisplay\n");
while(ptr1!=NULL)
{
printf("%d\n",ptr1->no);
ptr1=ptr1->next;
}
}


for more codes you can visit http://codesofprogramming.blogspot.in/

No comments:

Post a Comment