Saturday, May 9, 2009

PROGRAM FOR IMPLEMENTING SINGLR LINKED LIST

#include
#include
#include
#define NULL 0
struct slist
{
int info;
struct slist *next;
};
typedef struct slist node;
node *root,*new1,*prev,*list,*start,*temp;
int ele;
void create()
{
printf("Type -999 to stop");
scanf("%d",&ele);
while(ele!=-999)
{
new1=(node *)malloc(sizeof(node));
new1->info=ele;
new1->next=NULL;
if(root==NULL)
root=new1;
else
prev->next=new1;
prev=new1;
scanf("%d",&ele);
}
}
void print()
{
list=root;
if(root==NULL)
printf("list is empty");
else
{
printf("\n contents of list");
printf("root->");
while(list!=NULL)
{
printf("%d->",list->info);
list=list->next;
}
printf("NULL");
}
}

void delet()
{
int item;
node *p;
printf("Enter the element to be deleted");
scanf("%d",&item);
if(root->info==item)
{
p=root;
root=root->next;
free(p);
}
else
{
temp=root;
while((item!=temp->info)&&(temp!=NULL))
{
prev=temp;
temp=temp->next;
}
if(item==temp->info)
{
prev->next=temp->next;
free(temp);
}
}
}



void main()
{
int ch;
root=NULL;
do
{
printf("\n 1->creation");
printf("\n 2->deletion");
printf("\n 3->exit");
printf("\n Enter the choice");
scanf("%d",&ch);
switch(ch)
{
case 1: create();
print();
break;
case 2: delet();
print();
break;
case 3: exit(0);
break;
default: printf("Invalid choice");
}
} while(ch!=3);
getch();
}

No comments:

Post a Comment