Given a sorted Linked List, make sure new element is inserted in sorted way
Algorithm Used
Below 15 is to be inserted in sorted linked list.
#include <iostream>
using namespace std;
struct Node
{
Node * next;
int data;
};
void Insert ( Node **start,int d )
{
Node *cur;
if ( ( *start ) ==NULL || ( *start )->data>=d )
{
Node *newNode=new Node;
newNode->data=d;
newNode->next=*start;
( *start ) =newNode;
}
else
{
cur=*start;
while ( cur->next!=NULL&& ( cur )->next->data<=d )
{
cur= ( cur )->next;
}
Node *newNode=new Node;
newNode->data=d;
newNode->next= cur->next;
cur->next= newNode;
}
}
void Display ( Node *start )
{
while ( start!=NULL )
{
if ( start->next!=NULL ) {
cout<<start->data<<"->";
}
else {
cout<<start->data;
}
start=start->next;
}
}
int main()
{
Node *start=NULL;
Insert ( &start,35 );
Insert ( &start,20 );
Insert ( &start,10 );
Insert ( &start,25 );
Insert ( &start,15 );
Display ( start );
getchar();
}
Please comment if you find anything incorrect.
Reference:
Algorithm Used
- If Linked list is empty then make the node as head and return it.
- If value of the node to be inserted is smaller than or equal to value of head node then insert the node at start and make it head.
- In a loop, find the appropriate node after which the input data is to be inserted. To find the appropriate node start from head, keep moving until you reach a node who's value is greater than the input node.
- Insert the node after the appropriate node found in step 3.
Below 15 is to be inserted in sorted linked list.
#include <iostream>
using namespace std;
struct Node
{
Node * next;
int data;
};
void Insert ( Node **start,int d )
{
Node *cur;
if ( ( *start ) ==NULL || ( *start )->data>=d )
{
Node *newNode=new Node;
newNode->data=d;
newNode->next=*start;
( *start ) =newNode;
}
else
{
cur=*start;
while ( cur->next!=NULL&& ( cur )->next->data<=d )
{
cur= ( cur )->next;
}
Node *newNode=new Node;
newNode->data=d;
newNode->next= cur->next;
cur->next= newNode;
}
}
void Display ( Node *start )
{
while ( start!=NULL )
{
if ( start->next!=NULL ) {
cout<<start->data<<"->";
}
else {
cout<<start->data;
}
start=start->next;
}
}
int main()
{
Node *start=NULL;
Insert ( &start,35 );
Insert ( &start,20 );
Insert ( &start,10 );
Insert ( &start,25 );
Insert ( &start,15 );
Display ( start );
getchar();
}
Please comment if you find anything incorrect.
Reference:
- http://www.geeksforgeeks.org/given-a-linked-list-which-is-sorted-how-will-you-insert-in-sorted-way/
No comments:
Post a Comment