首页 > 编程 > C++ > 正文

图 简单滴C++邻接表 无向图

2019-11-08 19:49:34
字体:
来源:转载
供稿:网友

这个邻接表。。就是一个结构体数组。存放着 顶点信息和下一个点的信息。下一个点存着下一个点的信息。有点像简单的哈希表那样子

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");}这个是测试 这个没限制输入 。可以乱输入的 如果限制。加几句判断好了。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选