PROGRAM TO INSERT ELEMENTS IN THE SORTED LINKED LIST

/*PROGRAM TO INSERT ELEMENTS IN THE SORTED LINKED LIST*/
#include<conio.h>
#include<iostream.h>
struct node
{
int data;
struct node *link;
};
void main()
{
struct node *start=NULL,*ptr,*temp,*ptr1,*ptr2;
int num;
char ch;
clrscr();
cout<<“Inserting elements in the list:”<<endl;
do
{
temp=new node;
cout<<“Enter element: “;
cin>>num;
temp->data=num;
if(start==NULL||start->data>=temp->data)
{
temp->link=start;
start=temp;
}
else
{
ptr1=start;
ptr2=start->link;
while(ptr2!=NULL&&ptr2->data<=temp->data)
{
ptr1=ptr2;
ptr2=ptr2->link;
}
temp->link=ptr1->link;
ptr1->link=temp;
}
cout<<“Do you want to continue?? “;
cin>>ch;
}while(ch==’y’||ch==’Y’);
cout<<“Elements of list are”<<endl;
for(ptr=start;ptr!=NULL;ptr=ptr->link)
{
cout<<ptr->data<<“\t”;
}
getch();
}

Leave a Reply

Your email address will not be published. Required fields are marked *