Sunday, October 19, 2014

Concatenate or Merge two Linklists in C++

#include<iostream.h>
#include<conio.h>
class node
{
public:
int value,size;
node *nextnode,*headnode;
node *lastnode,*currentnode;
public:
node();
void add(int);
int get()
{
return value;
}
void set(int value)
{
this->value=value;
}
void setnext(node *nextnode)
{
this->nextnode=nextnode;
}
node *getnext()
{
return nextnode;
}

void  display()
{ cout<<"headnode hold: "<<headnode->getnext()<<endl;
for(node *a=headnode->getnext();a->getnext()!=NULL;a=a->getnext())
{

cout<<"Adress of  node:  "<<a<<"      Adress holdin /next node:  "<<a->getnext()<<endl;
cout<<"value of node:  "<<a->value<<endl<<endl;

}
}
friend void  conc( node c,node b)
{
c.currentnode->setnext(b.headnode->getnext());
delete b.headnode;
}
};
node::node()
{
headnode=new node();
headnode->setnext(NULL);
currentnode=NULL;
size=0;
}
void node::add(int n)
{
node *newnode=new node();
newnode->set(n);
if(currentnode!=NULL)
{
nextnode->setnext(currentnode->getnext());
currentnode->setnext(newnode);
lastnode=currentnode;
currentnode=newnode;
}
else
{
newnode->setnext(NULL);
headnode->setnext(newnode);
lastnode=headnode;
currentnode=newnode;

}
size++;
}
void main()
{
clrscr();
node obj,bol;
obj.add(11);
obj.add(20);
obj.add(30);
obj.add(40);
obj.display();
cout<<"Press any key to see 2nd link list: ";
getch();
clrscr();
cout<<endl<<"XXXXXXXXXXXXXXXXX"<<endl;
bol.add(25);
bol.add(23);
bol.add(22);
bol.display();
cout<<"Press any key to see 1st link list after concatination or merging ";
getch();
clrscr();
conc(obj,bol);
obj.display();
getch();
}

Share this

3 Comments to "Concatenate or Merge two Linklists in C++"