September 22, 2012 / IST / Science & Technology.

Sorting is one of the most important operations performed by computers. In the days of magnetic tape storage before modern data-bases, it was almost certainly the most common operation performed by computers as most “database” updating was done by sorting transactions and merging them with a master file. It’s still important for presentation of data extracted from databases: most people prefer to get reports sorted into some relevant order before wading through pages of data!

/* Q-13-> WAP a Program in C++ to Create a Sorted One Way Linked List with n Nodes.Extend the Program To Insert a New Node at appropriate  Location so that Order Does Not Get Disturbed*/

#include<iostream.h>
#include<conio.h>
#include<process.h>
class lnkdlst               //class declaration
{
   private:
	    struct Node
	    { int info;                //Node Structure
	      Node *next;
	     }*ptr,*first,*track,*temp,*x,*last;
   public:
	  lnkdlst()                     //Constructor
	  {ptr=first=track=temp=NULL;}
	  void insert(int);          //Member Functions
	  void display();
};
void lnkdlst::insert(int n)           //Function to insert Node
{
   ptr=new Node;
      if(ptr==NULL)
	{ cout<<"\nNode Cannot Be Created!!!";
	  getch();
	  exit(0);
	 }
   ptr->info=n;
   ptr->next=NULL;

   if(first==NULL)
      first=ptr;
   else if(ptr->info<first->info)
      {
       ptr->next=first;
       first=ptr;
      }
   else if(ptr->info>first->info)
      { track=x=first;
	while(track!=NULL)
	  {  x=track->next;
	     if(track->info<ptr->info && x==NULL)
		 {
		  track->next=ptr;
		  last=ptr;
		 }
	     else if(track->info<ptr->info && x->info>ptr->info)
		 {track->next=ptr;
		  ptr->next=x;
		 }
	      else if(last->info<ptr->info)
		  {
		   last->next=ptr;
		  }
	     track=track->next;
	   }
      }
}
void lnkdlst::display()             //Function to display the list
{
  temp=first;
   if(first==NULL)
      {cout<<"\nList Is Empty!!!";}
  while(temp!=NULL)
   {
     cout<<temp->info<<"  ";
     temp=temp->next;
   }
}
void main()                     //main
{
  lnkdlst ob;
  char choice;
  int data,ch;
  do
  { clrscr();
    cout<<"\n\n\t\t\tCREATION OF A SORTED LINKED LIST";
    cout<<"\n\t\t\t---------------------------------";
    cout<<"\n\n1.INSERT ELEMENT";
    cout<<"\n2.DISPLAY LIST";         //menu
    cout<<"\n3.EXIT";
    cout<<"\n\nWhich Operation Do You Want To Perform:";
    cin>>ch;
	 switch(ch)
	      {
		 case 1: cout<<"\nEnter the Data To Be Inserted:";
			 cin>>data;
			 ob.insert(data);
			 break;
		 case 2: ob.display();
			 break;             //calling functions
		 case 3: exit(1);
		 default: cout<<"\nPleasae Enter A valid Choice(1-4)!!!";
	       }
    cout<<"\n\nDo you Want to Continue(Y/N):";
    cin>>choice;
   }while(choice=='Y' || choice=='y');
}                   //end of program