這個鄰接表。。就是一個結構體數組。存放著 頂點信息和下一個點的信息。下一個點存著下一個點的信息。有點像簡單的哈希表那樣子
struct PHead head[i]
{
char VInfo 這個是每個節點的信息 栗子:A B C三個節點 VInfo 分別是A B C 就存儲了頭結點信息。我是char的嘛。。
node 這個就是每個數組保存的鏈表的第一個節點
}
struct Node
{
int V;//這個存儲的是與誰有關聯 栗子 V=5 表示這個節點與第5個節點關聯 也就是head[4].node
int w;//這個是權值。
Node*pNext;//鏈表嘛。指向下一個
}
初始化
head =new PHead[5];//醬紫就是5個結構體數組
for(頂點數量)head[i].node=nullptr head[i].data=char
for(邊的數量)這里要輸入起點終點 b e w表示哪兩個點相連 輸入權值 就可以插入了
Node *p p->v=b p->w=w p->pNext=head[i].node head[i].node=p//就構建完成了。
完整馬 3頂點 3個邊
#ifndef H_H#define H_H#include <iostream>using namespace std;struct Node{ int Vex; int W; Node*pNext;};struct pHead{ char data; Node *node;};class Head{public: Head(int m, int n); ~Head(); void show();PRivate: int m; int n; pHead *pnode;};Head::Head(int m, int n) :m(m), n(n){ pnode = new pHead[m];for (int i = 0; i < m; i++) { char c; cin >> c; pnode[i].data = c; pnode[i].node = nullptr; } for (int i = 0; i < n; i++) { int beg; int ed; int weight; cin >> beg >> ed >> weight; Node *p = new Node;if(!p)return; p->Vex = beg - 1; p->W = weight; p->pNext = pnode[ed - 1].node; pnode[ed - 1].node = p; } show();}Head::~Head(){ for (int i = 0; i < m; i++) { cout << pnode[i].data << " "; Node*p = pnode[i].node;while (p) { Node*d = p; p = p->pNext; delete d; d = nullptr; } cout << "over" << endl; } delete []pnode;}void Head::show(){ for (int i = 0; i < m; i++) { cout << pnode[i].data << "/n"; Node*p = pnode[i].node;while (p) { cout << p->Vex <<" to "<<i<< " W is "<<p->W<<" /n"; p = p->pNext; } }}#endif //H_H#include "h.h"int main(){ Head hd(3,3); system("pause");}這個是測試 這個沒限制輸入 。可以亂輸入的 如果限制。加幾句判斷好了。
新聞熱點
疑難解答
圖片精選