C++實(shí)現(xiàn)有向圖鄰接表的構(gòu)建
本文實(shí)例為大家分享了C++實(shí)現(xiàn)有向圖鄰接表的構(gòu)建代碼,供大家參考,具體內(nèi)容如下
數(shù)據(jù)結(jié)構(gòu)里面的一道基礎(chǔ)題,分享下自己的寫法,驗(yàn)證可跑。

#include<iostream>
#include<string>
const int MAX = 20;
using namespace std;
struct ArcNode { //弧結(jié)點(diǎn)
int adjvex = -1; //所指頂點(diǎn)位置
ArcNode *nextarc = nullptr; //下一條狐指針
size_t info = 0; //弧信息
};
struct VNode { //頂點(diǎn)
string data = "0";
ArcNode *firstarc = nullptr; //第一條依附該頂點(diǎn)的弧的指針
};
struct Graph { //圖結(jié)構(gòu)
VNode vertices[MAX]; //全部頂點(diǎn)
int vexnum, arcnum; //頂點(diǎn)數(shù)和弧數(shù)
Graph(int m, int n) :vexnum(m), arcnum(n) {};
Graph() :vexnum(0), arcnum(0) {};
};
int main()
{
int vnum, anum, tempanum = 0;
cout << "輸入頂點(diǎn)數(shù):";
cin >> vnum;
cout << "輸入弧數(shù):";
cin >> anum;
cout << "\n\n";
Graph G(vnum, anum);
for (int i = 0; i != vnum; ++i) {
cout << "輸入結(jié)點(diǎn)" << i << "的信息:";
cin >> G.vertices[i].data;
if (tempanum != anum)
cout << "輸入依靠此結(jié)點(diǎn)的弧的信息(輸入-1以停止):\n";
else
cout << "已輸入所有弧的信息!\n";
bool first = true;
ArcNode *p, *temp;
for (int j = 0; (j != anum) && (tempanum != vnum); ++j) {
int pointto;
cout << "輸入弧" << tempanum << "所指向的頂點(diǎn)位置:";
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 << "頂點(diǎn)" << 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;
}

由于只是單純構(gòu)建基本的無(wú)權(quán)值有向圖鄰接表,里面的弧結(jié)構(gòu)中弧信息未利用到。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于C++實(shí)現(xiàn)BMI身體質(zhì)量指數(shù)計(jì)算工具
BMI(Body?Mass?Index,身體質(zhì)量指數(shù)),也稱為體重指數(shù),是一種常用的衡量成人人體肥胖程度的指標(biāo),本文就來(lái)用C++編寫一個(gè)簡(jiǎn)單的BMI計(jì)算工具吧2023-10-10
C語(yǔ)言 CRITICAL_SECTION用法案例詳解
這篇文章主要介紹了C語(yǔ)言 CRITICAL_SECTION用法案例詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
C++實(shí)現(xiàn)路口交通燈模擬系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)路口交通燈模擬系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
OpenCV圖像算法實(shí)現(xiàn)圖像切分圖像合并示例
這篇文章主要為大家介紹了python圖像算法OpenCV實(shí)現(xiàn)圖像切分圖像合并操作示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06

