//Insertion in Sorted Linked List
#include<iostream>
using namespace std;
struct node
{
int info;
node *link;
};
int main()
{
node *start,*p,*pp,*temp;
start=p=NULL;
//Creating Linked List
int n;
cout<<"Press [0] to Exit :: Input Elements To List :";
do
{
cin>>n;
if(n)
{
temp=new node;
temp->info=n;
temp->link=NULL;
if(start==NULL)
start=temp;
else
p->link=temp;
p=temp;
}
}while(n);
//printing nodes
p=start;
cout<<"Created Nodes are : ";
while(p)
{
cout<<p->info<<" ";
p=p->link;
}
//find Location and insert item
cout<<"Enter Item to Insert :";
int item;
cin>>item;
if(start==NULL)
{
temp=new node;
temp->info=item;
temp->link=NULL;
start=temp;
p=temp;
}
if(item<start->info)
{
p=start;
temp=new node;
temp->info=item;
temp->link=p;
start=temp;
p=temp;
}
pp=start;
p=start->link;
while(p!=NULL)
{
if(item<p->info)
{
temp=new node;
temp->info=item;
pp->link=temp;
temp->link=p;
break;
}
pp=p,p=p->link;
}
if(p==NULL)
{
temp=new node;
temp->info=item;
pp->link=temp;
temp->link=NULL;
}
//printing
p=start;
cout<<"After Insertion : ";
while(p)
{
cout<<p->info<<" ";
p=p->link;
}
return 0;
}
#include<iostream>
using namespace std;
struct node
{
int info;
node *link;
};
int main()
{
node *start,*p,*pp,*temp;
start=p=NULL;
//Creating Linked List
int n;
cout<<"Press [0] to Exit :: Input Elements To List :";
do
{
cin>>n;
if(n)
{
temp=new node;
temp->info=n;
temp->link=NULL;
if(start==NULL)
start=temp;
else
p->link=temp;
p=temp;
}
}while(n);
//printing nodes
p=start;
cout<<"Created Nodes are : ";
while(p)
{
cout<<p->info<<" ";
p=p->link;
}
//find Location and insert item
cout<<"Enter Item to Insert :";
int item;
cin>>item;
if(start==NULL)
{
temp=new node;
temp->info=item;
temp->link=NULL;
start=temp;
p=temp;
}
if(item<start->info)
{
p=start;
temp=new node;
temp->info=item;
temp->link=p;
start=temp;
p=temp;
}
pp=start;
p=start->link;
while(p!=NULL)
{
if(item<p->info)
{
temp=new node;
temp->info=item;
pp->link=temp;
temp->link=p;
break;
}
pp=p,p=p->link;
}
if(p==NULL)
{
temp=new node;
temp->info=item;
pp->link=temp;
temp->link=NULL;
}
//printing
p=start;
cout<<"After Insertion : ";
while(p)
{
cout<<p->info<<" ";
p=p->link;
}
return 0;
}
No comments:
Post a Comment