圖的鄰接表表示法

#include<iostream>

using namespace std;

#define MAX_VERTEX_NUM 50

typedef char VertexData;

//定義弧結點
typedef struct EdgeNode
{
  int adjvex;    //該弧指向頂點的位置
  VertexData data;
  EdgeNode *next;
}EdgeNode;

//定義表頭結點
typedef struct VetexNode
{
  VertexData data;
  EdgeNode *link;
}VetexNode;


//定義基於鄰接表的圖
typedef struct AdjList
{
  int vexNun,arcNun; //定義鄰接表的頂點數,弧數
  VetexNode vertex[MAX_VERTEX_NUM];
}AdjList;

//建立圖,包含表頭結點的初始化,及表頭結點所指向的邊鏈表

void CreateGraph(AdjList *adj,int *n)
{
  int e,s,d;        // 定義圖的邊數, s爲邊的起始位置(即表頭結點序號)d爲目的位置(即邊鏈表結點序號)
  cout<<"輸入頂點數(n)和邊數(e)\n";
  cin>>*n>>e;
  adj->arcNun=*n;
  adj->vexNun=e;
  EdgeNode *q=NULL;
  //初始化n個表頭結點
  for(int i=1;i<=*n;i++)
  {
     cout<<"輸入第"<<i<<"個結點的信息\n";
     cin>>adj->vertex[i].data;
     adj->vertex[i].link=NULL;
  }
  for(i=1;i<=e;i++)
  {
    cout<<"請輸入邊的起始與目的位置\n";
    cin>>s>>d;
    cout<<"請輸入目的結點的信息\n";
    q=(EdgeNode *)malloc(sizeof(EdgeNode));
    if(q==NULL) return;
    q->adjvex=d;
    cin>>q->data;
    q->next=adj->vertex[s].link;
    adj->vertex[s].link=q;
  }
}

//打印圖的各個邊
void DispGraph(AdjList *adj)
{  
  int n=adj->arcNun;
  cout<<"全部的邊爲:\n";
  EdgeNode *q=NULL;
  for(int i=1;i<=n;i++)
  {
    q=adj->vertex[i].link;
    if(q==NULL)
    {
      cout<<"沒有從"<<adj->vertex[i].data<<"出發的結點\n";
    }
    else
    {
       cout<<"從結點"<<adj->vertex[i].data<<"出發的"<<"邊是\n";
       while(q!=NULL)
       {
          cout<<adj->vertex[i].data<<"->"<<q->data<<"\n";
          q=q->next;
        }
     }
  }
}

int main()
{
  int n;
  AdjList * adj=(AdjList *)malloc(sizeof(AdjList));
  CreateGraph(adj,&n);
  DispGraph(adj);
  return 0;
}
相關文章
相關標籤/搜索