Program to implement Single Linked List


//Implementation of Single Linked List

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void insert(int a,int b);
void dis();
void search(int c);
void del(int d);
void len();
void empty();
int l=0,f=0;
struct list
{
int data;
struct list *link;
}*first;
void dis()
{
struct list *cu;
printf(“\n”);
for(cu=first;cu;cu=cu->link)
{
printf(“%d”,cu->data);
if(cu->link!=NULL)
printf(“->”);
}
}
void len()
{
struct list *cur;
for(cur=first;cur;cur=cur->link)
{
l++;
}
printf(“\n The size of the list is:%d\n”,l);
}
void empty()
{
if(first==0)
{
printf(“\n The List is empty”);
}
else
{
printf(“The list is not empty\n”);
}
}
void search(int g)
{
struct list *p=first;
for(p=first;p;p=p->link)
{
if(p->data==g)
{
printf(“\n The element is Present\n”);
f=0;
break;
}
else
{
f=1;
}
}
if(f==1)
{
printf(“\n Element is not present\n”);
}
}
void del(int u)
{
int i;
struct list *cu=first,*q=first;
for(i=1;i<u;i++)
cu=cu->link;
for(i=1;i<=u;i++)
q=q->link;
if(u)
{
cu->link=q->link;
delete(q);
}
else if(cu->link!=NULL && q->link==NULL)
{
cu->link=NULL;
delete(q);
}
if(u==0)
{
first=q->link;
delete(q);
}
}
void insert(int a,int b)
{
int i;
struct list *p=first,*q;
q=(struct list*)malloc(sizeof(struct list*));
for(i=1;i<a;i++)
{
p=p->link;
}
q->data=b;
if(a)
{
q->link=p->link;
p->link=q;
}
else
{
q->link=first;
first=q;
}
}
void main()
{
first=(struct list*)malloc(sizeof(struct list*));
first=0;
int c,p,v,s,d;
clrscr();
do
{
printf(“\n1.Insert\n2.Delete\n3.display\n4.search\n5.Lenth\n6.Empty\n7.Exit\n”);
printf(“\n Enter your Choice:\n”);
scanf(“%d”,&c);
switch(c)
{
case 5:
len();
break;
case 6:
empty();
break;
case 1:
printf(“\n Enter the position and value:\n”);
scanf(“%d%d”,&p,&v);
insert(p,v);
break;
case 2:
printf(“\nenter the position to delete:\n”);
scanf(“%d”,&d);
del(d);
break;
case 3:
printf(“\n The Elements are:\n”);
dis();
break;
case 4:
printf(“\n Enter the element to search:\n”);
scanf(“%d”,&s);
search(s);
break;
default:
printf(“\n Exit Choice\n”);
}
}while(c!=7);
getch();
}

Advertisements

2 thoughts on “Program to implement Single Linked List

  1. please clarify my doubt sir…………. in data structure for semester exam we have to write algorithm or program?

    • Based on the mark allotted for that question…
      for 16 marks it is always suggested to write both … but when u write program don’t give much importance to main() function…

      For example, if you write algorithm for PUSH operation, following that you can write the program code for that algorithm

Comments are closed.