A program to split a Link List.

 

#include<iostream.h>
#include<conio.h>

struct node
{
int data;
node *link;
};

node *start,*new_start,*x,*y;

void create()
{
if(start==NULL)
{
start=new node;
cout<<"\nEnter data: ";
cin>>start->data;
start->link=NULL;
x=start;
}
else
{
y=new node;
cout<<"\nEnter data: ";
cin>>y->data;
y->link=NULL;
x->link=y;
x=y;
}
}

void display1()
{
x=start;

cout<<"\nLink list: ";
while(x!=NULL)
{
cout<<x->data<<" ";
x=x->link;
}
cout<<endl;
}

void split_linklist()
{
int n,i=0;
x=start;
while(x!=NULL)
{
i++;
x=x->link;
}
if(i==0 || i==1)
cout<<"Link list cannot be splitted."<<endl;
else
{
x=start;
y=x->link;
cout<<"\nEnter data value of node after which link list is to be split: ";
cin>>n;
while(x->data!=n && x!=NULL)
{
x=x->link;
y=y->link;
}
if(x->data==n)
{
new_start=y;
x->link=NULL;
}
else
cout<<"Data value not present."<<endl;
}
}

void display2()
{
x=start;
cout<<"\nFirst link list: ";
while(x!=NULL)
{
cout<<x->data<<" ";
x=x->link;
}
cout<<endl;

x=new_start;
cout<<"\nSecond link list: ";
while(x!=NULL)
{
cout<<x->data<<" ";
x=x->link;
}
cout<<endl;
}

void main()
{
 clrscr();

 start=NULL;

 int ch;

 do
  {
   cout<<"1. Create a node."<<endl;
   cout<<"2. Display Link List"<<endl;
   cout<<" (before splitting or the 1st link list after splitting)"<<endl;
   cout<<"3. Split the Link List."<<endl;
   cout<<"4. Display the two splitted Link Lists."<<endl;
   cout<<"5. Exit."<<endl;
   cout<<"Enter your choice: ";
   cin>>ch;

   switch(ch)
    {
     case 1: {
                 create();
                 break;
                }
     case 2: {
                 display1();
                 break;
                }
     case 3: {
                 split_linklist();
                 break;
                }
     case 4: {
                 display2();
                 break;
                }
     case 5: {
                 break;
                }
     default: {
                 cout<<"\nWrong choice entered.\n";
                }
    }
   cout<<endl;
  }
 while(ch!=5);
}

 

< Back