1. 程式人生 > 程式設計 >C++實現有向圖鄰接表的構建

C++實現有向圖鄰接表的構建

本文例項為大家分享了C++實現有向圖鄰接表的構建程式碼,供大家參考,具體內容如下

資料結構裡面的一道基礎題,分享下自己的寫法,驗證可跑。

C++實現有向圖鄰接表的構建

#include<iostream>
#include<string>
const int MAX = 20;
using namespace std;
 
 
struct ArcNode {      //弧結點
 int adjvex = -1;     //所指頂點位置
 ArcNode *nextarc = nullptr; //下一條狐指標
 size_t info = 0;  //弧資訊
};
 
 
struct VNode {      //頂點
 string data = "0";
 ArcNode *firstarc = nullptr; //第一條依附該頂點的弧的指標
};
 
 
struct Graph {      //圖結構
 VNode vertices[MAX];         //全部頂點
 int vexnum,arcnum;     //頂點數和弧數
 Graph(int m,int n) :vexnum(m),arcnum(n) {};
 Graph() :vexnum(0),arcnum(0) {};
};
 
 
int main()
{
 int vnum,anum,tempanum = 0;
 cout << "輸入頂點數:";
 cin >> vnum;
 cout << "輸入弧數:";
 cin >> anum;
 cout << "\n\n";
 Graph G(vnum,anum);
 for (int i = 0; i != vnum; ++i) {
 cout << "輸入結點" << i << "的資訊:";
 cin >> G.vertices[i].data;
 if (tempanum != anum)
  cout << "輸入依靠此結點的弧的資訊(輸入-1以停止):\n";
 else
  cout << "已輸入所有弧的資訊!\n";
 bool first = true;
 ArcNode *p,*temp;
 for (int j = 0; (j != anum) && (tempanum != vnum); ++j) {
  int pointto;
  cout << "輸入弧" << tempanum << "所指向的頂點位置:";
  cin >> pointto;
  if (pointto == -1) break;
  else {
  ++tempanum;
  if (first == true) {
   first = false;
   G.vertices[i].firstarc = new ArcNode;
   G.vertices[i].firstarc->adjvex = pointto;
   p = G.vertices[i].firstarc;
  }
  else {
   temp = new ArcNode;
   temp->adjvex = pointto;
   p->nextarc = temp;
   p = temp;
  }
  }
 }
 cout << endl;
 }
 
 for (int i = 0; i != anum; ++i) {
 cout << "頂點" << i << ": |" << G.vertices[i].data << "|";
 if (G.vertices[i].firstarc) {
  cout << " -> " << G.vertices[i].firstarc->adjvex;
  auto pt = G.vertices[i].firstarc->nextarc;
  while (pt) {
  cout << " -> " << pt->adjvex;
  pt = pt->nextarc;
  }
  cout << "-> ^";
 }
 else
  cout << " -> ^";
 cout << endl;
 }
 return 0;
}

C++實現有向圖鄰接表的構建

由於只是單純構建基本的無權值有向圖鄰接表,裡面的弧結構中弧資訊未利用到。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。