Monday 20 December 2010

Program that uses functions to perform the following operations on single linked lists. i) creation ii) insertion iii) traversal

Description:


In this program we have to create a single linked list, insert the elements into that list ,delete the some elements from that list and then perform the sorting operation and traversal operation on that created linked list

Program:


# include<stdio.h> 
# include<malloc.h> 

int  ch,i,n,j,p,item; /* VARIABLE DECLARATION */

/* START OF STRUCTURE DEFINITION */

struct link
{
int data;
struct link *next; }*start,*new,*l,*l1,*start1,*t;

/* END OF STRUCTURE DEFINITION */

/* START OF MAIN FUNCTION */

void main()
{
clrscr();
start=NULL;
start1=NULL;
printf(" **** MENU **** ");
printf("\n 1.Insertion\n 2.Traverse\n 3.Exit\n");
   while(1)
     {
printf("enter the choice:"); scanf("%d",&ch); 
switch(ch)

{
case 1: insert(); break;

case 2: traverse(); 
break; case3: exit();

}
   }
getch();
        }

/* END OF MAIN FUNCTION */



/* START OF INSERT FUNCTION */

insert()
{
l=start;
printf("enter the item to be inserted:"); scanf("%d",&item); new=malloc(sizeof(struct link));
 new->data=item;
if(start==NULL)
{
new->next=NULL; start=new;

}
else
{
printf("1.start\n2.middle\n3.end\n");
 printf("enter the place to place the item:");

scanf("%d",&ch);
if(ch==1)
{
new->next=start; start=new;

}
if(ch==2)
{
printf("enter the position to place item:"); scanf("%d",&p);
for(i=1;i<p-1;i++)
 l=l->next; 
new->next=l->next;
 l->next=new;
}
if(ch==3)
{
while(l->next!=NULL)
 l=l->next;
new->next=NULL; 
l->next=new;

}
}
}

/* END OF INSERT FUNCTION */


/* START OF DISPLAY FUNCTION */

traverse()
{
if(start==NULL) 
printf("LIST IS EMPTY\n"); 
else
{
for(l=start;l->next!=NULL;l=l->next) if(l==start)
 printf("\nstart:%d->",l->data);
else 
printf("\n%7d->",l->data); 
if(l->next==NULL)
printf("\n last:%d->\n",l->data);
}
}

/* END OF DISPLAY FUNCTION */

}


***** OUTPUT ***** 
****   MENU     **** 
1.Insertion 
2.Traverse
3.Exit
enter the choice:1
enter the item to be inserted:1
 enter the choice:1

enter the item to be inserted:2 1.start
2.middle
3.end
enter the place to place the item:1 
enter the choice:1
enter the item to be inserted:3 
1.start
2.middle
3.end
enter the place to place the item:3 enter the choice:1
enter the item to be inserted:4 1.start
2.middle
3.end

enter the place to place the item:2 
enter the position to place item:3

 enter the choice:2

start:2->
       1->
       4-> 
last:3->

Conclusion: the program is error free

VIVA QUESTIONS:


1)List out the memory allocation functions ? 
Ans: malloc(), calloc(),free(), realloc() etc.., 


2)Define linked list ? 
Ans: Linked list is list whose order is given by links from one item to the next

3)List out the advantages of linked list ?
 Ans:  Dyanamic data structure

no waste memory space 
     flexibility 





Single Linked List in c++

What is  Linked list

No comments:

Post a Comment