鄰接表


#include <iostream>
#include "stdio.h"
#include "stdlib.h"
#include "cstdlib"//syste()函數需要該頭文件;

using namespace std;

#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;

typedef char VerTexType;
typedef int ArcType;
#define MVNum 100 //最大頂點數

//00 定義邊結點 頂點結點 鄰接表

 typedef struct ArcNode{ //邊結點 

  int adjvex;      //該邊所指向的頂點的位置,數組中的位置,下標0開始
  ArcType weight;    //和邊相關的信息
  struct ArcNode * nextarc; //指向下一條邊的指針
}ArcNode;

typedef struct VNode{
  VerTexType data; //頂點信息
  ArcNode * firstarc; //指向第一條依附該頂點的邊的指針,用到ArcNode類型,故放在邊定義后
}VNode, AdjList[MVNum]; //AdjList表示鄰接表類型,數組,里面是VNode型數據

typedef struct{
  AdjList adjList; //鄰接表,adjList是個VNode型數組,用來放頂點及鄰接表指針
  int vexnum, arcnum; //圖的當前頂點數和邊數
}ALGraph;

//01 定位

 int LocateVex(ALGraph G,char ch)

{
  int i;
  for(i=0;i<G.vexnum;i++){
    if(ch==G.adjList[i].data)
      return i;//return返回,下面-1不執行了。
  }
  return -1;
}

//02 創建,注意是圖 有向圖 網,不一樣,里面代碼也不同

Status CreateALGraph(ALGraph &G)
{
  int i,j,k,w;//無向圖權值可以不要,可以置0,后面不用輸入
  ArcNode *p1,*p2;//p1將來放到鄰接表數組中的指針域,故聲明指針型
  char v1,v2;
  printf("Input the number of vertex and arc:\n");
  cin>>G.vexnum>>G.arcnum;
  printf("The number is %d and %d.\n",G.vexnum,G.arcnum);//驗證輸入內容

  for(i=0;i<G.vexnum;i++)
  {
    cin>>G.adjList[i].data;
    G.adjList[i].firstarc=NULL;
  }

  //build 邊表,構造的是無向圖,書本中的例子
  for(k=0;k<G.arcnum;k++)
  {
    printf("輸入邊(vi,vj)上的頂點序號及權值:\n");
    cin>>v1>>v2>>w;

    i=LocateVex(G,v1);
    j=LocateVex(G,v2);
    cout<<i<<"和"<<j<<endl;//驗證
    if(i==-1 || j==-1){
      return ERROR;
    }

    //申請內存空間生成邊表結點,單鏈表前插法
    p1=new ArcNode;
    if(p1==NULL)
    {
      return ERROR;
    }
    p1->adjvex=j;
    p1->weight=w;
    p1->nextarc=G.adjList[i].firstarc;//注意畫個圖
    G.adjList[i].firstarc=p1;//前面最好聲明p1為指針型


    //無向圖有這一步,有向圖就不需要了
    p2=new ArcNode;
    if(p2==NULL)
      return ERROR;
    p2->adjvex=i;
    p2->weight=w;
    p2->nextarc=G.adjList[j].firstarc;//注意畫個圖
    G.adjList[j].firstarc=p2;//此處賦值為指針,故前面最好聲明p1為指針型
  }
  return OK;
}

//03打印
void PrintALGraphArc(ALGraph G)
{
  int i=0;
  ArcNode *p=NULL;
  while(G.adjList[i].firstarc!=NULL && i<G.vexnum)
  {
    printf("頂點%c與這些點連接:",G.adjList[i].data);

    p=G.adjList[i].firstarc;

    while(p!=NULL){
      printf("%d %c ",p->adjvex,G.adjList[p->adjvex]); //打印邊表的節點
      p=p->nextarc;
    }
    i++;
  printf("\n");
  }
}

int main()
{
  ALGraph G;
  CreateALGraph(G);
  PrintALGraphArc(G);
  system("pause");
  return OK;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM