歡迎您光臨本站 註冊首頁

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

←手機掃碼閱讀     火星人 @ 2020-04-28 , reply:0

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

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

#include

#includeconst 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 << "



"; Graph G(vnum, anum); for (int i = 0; i != vnum; ++i) { cout << "輸入結點" << i << "的信息:"; cin >> G.vertices[i].data; if (tempanum != anum) cout << "輸入依靠此結點的弧的信息(輸入-1以停止):

"; else cout << "已輸入所有弧的信息!

"; 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++實現有向圖鄰接表的構建已經有128次圍觀

http://coctec.com/docs/c/language/show-post-231976.html