有向图十字链表创建与输出(一)

#include <iostream>


using namespace std;


template <class TElemType>
class Graph
{
public:
     void CreateOlgraph();
     void PrintOlgraph();
private:
      struct ArcBox
  {
   int headvex,tailvex;
   ArcBox *hlink,*tlink;
   float weight;
  };


  template <class TElemType>
  struct Vertex
  {
   TElemType data;
   ArcBox *firstin,*firstout;
  };


  struct Olgraph
  {
   int vexnum,arcnum;
   Vertex<TElemType> *vex;
  };
  Olgraph olgraph;               //有向图的十字链表存储结构




};


template <class TElemType>
void Graph<TElemType>::CreateOlgraph()  // 创建十字链表
{
 int i,j,m,n;
 float w;
 TElemType v1,v2;
 ArcBox *p;
 cout << "输入有向图的顶点数和边数:" << endl;
 cin >> olgraph.vexnum >> olgraph.arcnum;
 olgraph.vex = (Vertex<TElemType> *)malloc(olgraph.vexnum * sizeof(Vertex<TElemType>));
 cout << "输入顶点的信息:" << endl;
 for(i = 0;i < olgraph.vexnum;i++)
 {
  cin >> olgraph.vex[i].data;
  olgraph.vex[i].firstin = olgraph.vex[i].firstout = NULL;
 }


 cout << "输入各边的弧尾与弧头结点及有向边的权值:" << endl;


 for(i = 0;i < olgraph.arcnum;i++)
 {
  cin >> v1 >> v2 >> w;
  for(j = 0;j < olgraph.vexnum;j++)
  {
   if(v1 == olgraph.vex[j].data) m = j;
   if(v2 == olgraph.vex[j].data) n = j;
  }
  p = (ArcBox *)malloc(sizeof(ArcBox));
  p->headvex = n;p->tailvex = m;
  p->weight = w;
  p->hlink = olgraph.vex[n].firstin;olgraph.vex[n].firstin = p;
  p->tlink = olgraph.vex[m].firstout;olgraph.vex[m].firstout = p;
 }
}         //end CreateOlgraph




template <class TElemType>
void Graph<TElemType>::PrintOlgraph()  // 输出十字链表
{
  int k;
  ArcBox *p;
 cout << "    The Vertex Outdegree = >  " << endl;
  for(k = 0; k <olgraph.vexnum; k ++)
  {  
     p = olgraph.vex[k].firstout;
     cout << "    Vertex:" << k+1 << "";
     while(p != NULL)
     {
        
     cout << "<"<<(p->tailvex)+1 << "," << (p->headvex)+1<< ">" << " ";
     p = p-> tlink;
      
    }
      cout << endl;
    
  }


  


   cout << "    The Vertex Indegree = >  " << endl;
  for(k = 0; k <olgraph.vexnum; k ++)
  {  
     p = olgraph.vex[k].firstin;
     cout << "    Vertex:" << k+1 << "";
     while(p != NULL)
     {
        
     cout << "<"<<(p->tailvex)+1 << "," << (p->headvex)+1<< ">" << " ";
     p = p-> hlink;
      
     }
      cout << endl;
    
  }


}


int main()
{
 /*Graph<int> gph;
 gph.CreateDN();
 int a,b;
 cout << "输入终点和起点:";
 cin >> a >> b;
 gph.Shortestpath_DIJ(a,b);
 gph.DestroyDN();
 return 0;*/
 Graph<int> gph;
 gph.CreateOlgraph();
 gph.PrintOlgraph();


 return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值