Showing posts with label Advanced Data Structures. Show all posts
Showing posts with label Advanced Data Structures. Show all posts

Sunday, 15 April 2018

Graph representation with matrix and linked list

#include<iostream>
using namespace std;
struct node
{
   int data;
   node *next;
};
class Graph
{
     int G1[40][40];
     int i,j;
     node *b[40];
     public:
  void createmat(int);
  void showmat(int);
        void create(int );
  void show(int );
  void initg(int);
};
void Graph::initg(int n)
{
   for(i=1;i<=n;i++)
   { 
      for(j=1;j<=n;j++)
      {
         G1[i][j]=0;
      }
  }
}
void Graph::createmat(int n)
{
   int x;
   for(i=1;i<=n;i++)
   {

     for(j=1;j<=n;j++)
     {

        if(i==j)
        {

        }

       else if(G1[i][j]==0)
       {


            cout<<"Is there edge between"<<" "<<i<<" "<<"and"<<" "<<j<<": ";

            cin>>x;

            G1[i][j]=G1[j][i]=x;


      }

   }

 }

}



void Graph::showmat(int n)

{

     for(i=1;i<=n;i++)
    {

       for(j=1;j<=n;j++)
       {

           cout<<G1[i][j]<<"\t";

       }

       cout<<"\n";

  }
}
void Graph::create(int n)
{

 node *p,*temp;
 int x;
 char ch;
 for(i=1;i<=n;i++)
 {
  b[i]=NULL;
 }

 for(i=1;i<=n;i++)
 {
  cout<<"\nEnter vertex data : ";
  cin>>x;
  b[i]=new node;
  b[i]->data=x;
  b[i]->next=NULL;
  temp=b[i];
  do
  {
   cout<<"\nIs there any adjucent vertex to "<<" "<<b[i]->data;
   cin>>x;
   p=new node;
   p->data=x;
   p->next=NULL;
   temp->next=p;
   temp=p;
   cout<<"\nDo u want to continue ? ";
   cin>>ch;
  }while(ch=='y'||ch=='Y');
 }
}

void Graph::show(int n)
{
 node *p;
 for(i=1;i<=n;i++)
 {
  cout<<"\t"<<b[i]->data;
  p=b[i]->next;
  while(p!=NULL)
  {
   cout<<"-->"<<p->data;
   p=p->next;
  }
  cout<<"\n";
 }
}


int main()

{

 int n;

 cout<<"\nEnter how many vertices do you want to enter :";

 cin>>n;

 Graph g1;

 g1.initg(n);
 //g1.showmat(n);
g1.createmat(n);
g1.showmat(n);
 cout<<"Graph by using Adjucency List";
 cout<<"\nhow many verices";
 cin>>n;
 g1.create(n);
 cout<<"Adjucency List is \n";
 g1.show(n);

 return 0;

}

Binary Tree creation & inorder show

#include<iostream>
using namespace std;
struct node
{
string data;
node *Lc,*RC;
};
class BT
{
public:
node *create();
void show(node*);
};
node* BT::create()
{
string x;
node *p;
cout<<"enter Book Name -1 if Book is not available\n";
cin>>x;
if(x=="-1")
return NULL;
else
{
p=new node;
p->data=x;
p->Lc=NULL;
p->RC=NULL;
cout<<"enter LC of : "<<x<<"\n";
p->Lc=create();
cout<<"enter RC of : "<<x<<"\n";
p->RC=create();
}
return p;

}
void BT::show(node *ptr)
{
if(ptr!=NULL)
{
show(ptr->Lc);
cout<<ptr->data<<"-->";
show(ptr->RC);
}
}
int main()
{
BT b1;
node *root;
root=NULL;
root=b1.create();
cout<<"\nInorder....\n";
b1.show(root);
cout<<"\n";
cout<<"\nPreporder....\n";
b1.preorder(root);
cout<<"\n";
cout<<"Postorder...\n";
b1.postorder(root);
return 0;
}