Sunday, October 2, 2011

Data Structure C program singly linked list Dev c++

 #include <stdio.h>  
#include <conio.h>
void badd();
void eadd();
void madd();
void del();
void display();
struct node{
int data;
struct node* next;
};
typedef struct node position;
position* find(int);
position* start;
void badd()
{
position *temp=(position*)malloc(sizeof(position));
printf("Enter Data:");
scanf("%d",&temp->data);
if(start==NULL)
{
temp->next=NULL;
start=temp;
}
else
{
temp->next=start;
start=temp;
}
}
void eadd()//assuming that link list is not empty
{
position *temp=(position*)malloc(sizeof(position));
printf("Enter Data:");
scanf("%d",&temp->data);
position *temp2=start;
while(temp2->next!=NULL)
temp2=temp2->next;
temp2->next=temp;
temp->next=NULL;
}
position* find(int x)
{
position* temp=start;
while(temp->data!=x && temp!=NULL)
{
temp=temp->next;
}
return temp;
}
void madd()
{
int x;
position *temp=(position*)malloc(sizeof(position));
printf("Enter Data:");
scanf("%d",&temp->data);
printf("Enter element's value after which you want to add new data :");
scanf("%d",&x);
position *temp2=find(x);
if(temp2==NULL)
printf("Element not found\n");
else
{
temp->next=temp2->next;
temp2->next=temp;
}
}
void del()
{
int x;
position *temp,*prev;
printf("Enter element:");
scanf("%d",&x);
temp=start;
while(temp->data!=x && temp!=NULL)
{
prev=temp;
temp=temp->next;
}
if(!temp)
{
printf("NOT FOUND\n");
return;
}
if(temp==start)
{
start=start->next;
free(temp);
}
else
{
prev->next=temp->next;
free(temp);
}
}
void display()
{
if(start==NULL)
{
printf("EMPTY LINK LIST\n");
return;
}
position *temp=start;
printf("LINK LIST is:-\n");
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
printf("\n");
}
int main()
{
int ch;
printf("1.Add at start\n2.Add in between\n3.Add At the end\n4.Delete\n5.Display\n6.exit\n");
scanf("%d",&ch);
while(ch!=6)
{
switch(ch)
{
case 1:badd();
break;
case 2:madd();
break;
case 3:eadd();
break;
case 4:del();
break;
case 5:display();
break;
default:printf("WRONG CHOICE");
}
printf("1.Add at start\n2.Add in between\n3.Add At the end\n4.Delete\n5.Display\n6.exit\n");
scanf("%d",&ch);
}
}

No comments:

Post a Comment

Google+ Followers