C++實現有向圖鄰接表的構建
更新時間:2020年04月26日 14:12:19 作者:GetoWork
這篇文章主要為大家詳細介紹了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;
}

由于只是單純構建基本的無權值有向圖鄰接表,里面的弧結構中弧信息未利用到。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

