/* Implement singly linked list of integers using array */
#include <stdio.h>
#include <string.h>
#define MAX 30
typedef struct list
{ int head; //index of the front element
int data[MAX];
int next[MAX];//index of the successor
int flag[MAX];//flag[i] as 0 indicates absence of data
}list;
void insert( list *p,int position,int x);
void Delete(list *p,int position);
int search(list *p,int x);
void print(list *p);
void read(list *p);
void init(list *p);
int main()
{ list l;
int x,op,position;
do{
fflush(stdin);
printf("\n1)create\n2)insert\n3)delete\n4)search\n5)print\n6)quit");
printf("\nEnter Your Choice:");
scanf("%d",&op);
switch(op)
{ case 1: read(&l);
break;
case 2: printf("\n enter the position and the data to be inserted : ");
scanf("%d%d",&position,&x);
insert(&l,position,x);
break;
case 3:printf("\n enter the position : ");
scanf("%d",&position);
Delete(&l,position);
break;
case 4: printf("\nenter the number to be searched:");
scanf("%d",&x);
position=search(&l,x);
if(position==-1)
printf("\nnot found");
else
printf("Found at the position : %d",position+1);
break;
case 5: print(&l);
break;
default:break;
}
}while(op!=6);
}
void insert( list *p,int position,int x)
{ int i,j,pred;
//locate an empty location
for(j=0;p->flag[j]==1 && j<MAX ;j++);
if(j==MAX)
{
printf("\nOverflow....");
return;
}
p->data[j]=x;
p->flag[j]=1;
if(position==1)
{
p->next[j]=p->head;
p->head=j;
return;
}
//locate the predecessor
for(pred=p->head,i=1;i<position-1;i++)
{
if(pred==-1 || p->next[pred]==-1)
{
printf("\nOverflow...");
return;
}
else
pred=p->next[pred];
}
p->next[j]=p->next[pred];
p->next[pred]=j;
}
void Delete(list *p,int position)//delete a data from given position
{
int i,j,pred;
if(p->head==-1 || position <1)
{
printf("\nUnderflow...can not delete ");
return;
}
if(position==1)//first data to be deleted
{
p->flag[p->head]=0;
p->head=p->next[p->head];
return;
}
//locate the predecessor
for(pred=p->head,i=1;i<position-1;i++)
{
if(pred==-1 || p->next[pred]==-1)
{
printf("\nUnderflow...");
return;
}
else
pred=p->next[pred];
}
j=p->next[pred];//index of the element to be deleted
p->next[pred]=p->next[j];
p->flag[j]=0;
}
int search(list *p,int x)
{ int i, position=0;
if(p->head==-1)
return(-1);
for(i=p->head;i!=-1;i=p->next[i],position++)
if(x==p->data[i])
return(position);
return(-1);
}
void print(list *p)
{ int i;
printf("\n");
for(i=p->head;i!=-1;i=p->next[i])
printf("%d ",p->data[i]);
}
void read(list *p)
{ int i,n;
printf("\nEnter No. of data : ");
scanf("%d",&n);
printf("\Enter data : ");
for(i=0;i<n;i++)
{
scanf("%d", &(p->data[i]));
p->next[i]=i+1;
p->flag[i]=1;
}
p->next[n-1]=-1;
p->head=0;
}
void init(list *p)
{
int i;
for(i=0;i<MAX;i++)
{
p->flag[i]=0;
p->next[i]=-1;
}
p->head=-1;
}
No comments:
Post a Comment