Code:
//This has more functionalities.....it can search whether two vertices are connected or  not :smug::D
#include<malloc.h>
#include<conio.h>
#include<stdlib.h>
#include<iostream.h>

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

int nodes;

void display(struct node *a)
{ struct node *temp;
  for(int i=0;i<nodes;i++)
  { cout<<a[i].vertex;
     temp = &a[i];
     while(temp->link!=NULL)
     { temp = temp->link;
        cout<<"->"<<temp->vertex;
     }
     cout<<"\n";
  }
}
void search_connec(struct node *a ,int x,int y)
{  struct node *temp;
    temp = &a[x-1];
     while(temp->link!=NULL)
     { temp = temp->link;
        if(temp->vertex == y)
        { cout<<"\nVertex "<<x<<" is connected to vertex "<<y<<"\n";
          return;
        }
     }
     cout<<"\nNot connected";

}
void main()
{ int x,y,choice;
  char ch;
  struct node *temp,*t1;
  cout<<"\n Enter the number of vertices : ";
  cin>>nodes;
  node *a= (struct node*)malloc(nodes*(sizeof(struct node)));
  for(int i=1;i<=nodes;i++)
  {   a[i-1].vertex = i;
        cout<<"Is node "<<i<<" is connected to some other node(y/n):";
        cin>>ch;
        if((ch == 'y') || (ch == 'Y'))
        {
          temp = &a[i-1] ;
          cout<<"node no."<<i<<" is connected to :";
          while(ch=='Y' || ch=='y')
          { t1 = (struct node*)malloc(sizeof(struct node));
             cout<<"\nEnter vertex no.";
             cin>>t1->vertex;
             while(!((t1->vertex) <= nodes))
             { cout<<"\nInvalid node! Please re-enter correct node :";
                cin>>t1->vertex;
             }
             temp->link = t1;
             temp=t1;
             cout<<"\nAny other node(y/n):";
             cin>>ch;
          }
        temp->link=NULL;
        }
        else
        a[i-1].link=NULL;
  }
  do{
        cout<<"\n -------------------------- \n";
        cout<<"              MENU            \n";
        cout<<"\n -------------------------- \n";
        cout<<"      1.Display Graph         \n";
        cout<<"      2.Search Connection     \n";
        cout<<"\n    Enter your choice :       ";
        cin>>choice;
        switch(choice)
        {
         case 1: display(a);
                    break;
         case 2: clrscr();
                    cout<<"\n Enter source vertex :";
                    cin>>x;
                    cout<<"\n Enter destination vertex :";
                    cin>>y;
                    search_connec(a,x,y);
                    break;
         default : cout<<"\n Invalid choice";
                    break;
        }
     }while(choice==1 ||choice==2);
}

Last edited by shabbir; 18Feb2012 at 09:24.. Reason: Code blocks