資源簡介
使用鄰接表實現圖結構,無向的、有向的、無權的和有權的都可支持。
代碼片段和文件信息
#include
#include
using?namespace?std;
//最大權值
#define?MAXWEIGHT?100
//邊節點
typedef?struct?edgenode_tag
{
int?adjvex;??//鄰接點
int?weight;??//邊的權值
struct?edgenode_tag?*next;
}EdgeNode;
//頂點節點
typedef?struct?vertex_tag
{
int?vertex;???//頂點
EdgeNode?*next;
}Vertex;
class?Graph
{
private:
//是否帶權
bool?isWeighted;
//是否有向
bool?isDirected;
//頂點數
int?numV;
//邊數
int?numE;
//鄰接表
Vertex?*adjList;
public:
/*
構造方法
numV是頂點數,isWeighted是否帶權值,isDirected是否有方向
*/
Graph(int?numV?bool?isWeighted?=?false?bool?isDirected?=?false);
//建圖
void?createGraph();
//析構方法
~Graph();
//獲取頂點數
int?getVerNums()
{return?numV;}
//獲取邊數
int?getEdgeNums()
{return?numE;}
//插入邊
void?insertEdge(int?tail?int?head?int?weight?=?1);
void?insertedge(int?tail?int?head?int?weight);
//設置指定邊的權值
void?setEdgeWeight(int?tail?int?head?int?weight);
//打印鄰接表
void?printAdjacentList();
//檢查輸入
bool?check(int?tail?int?head?int?weight?=?1);
};
/*
構造方法
numV是頂點數,isWeighted是否帶權值,isDirected是否有方向
*/
Graph::Graph(int?numV?bool?isWeighted?bool?isDirected)
{
while?(numV?<=?0)
{
cout?<“輸入的頂點數不正確!,重新輸入?“;
cin?>>?numV;
}
this->numV?=?numV;
this->isWeighted?=?isWeighted;
this->isDirected?=?isDirected;
//邊數初始化為0
numE?=?0;
adjList?=?new?Vertex[numV];??//指針數組
for?(int?i?=?0;?i? {
adjList[i].vertex?=?i;
adjList[i].next?=?NULL;
}
}
//建圖
void?Graph::createGraph()
{
//用一個新的變量表示邊數,numE的修改則留到insertedge()中
int?numEdge?=?0;
cout?<“輸入邊數?“;
while?(cin?>>?numEdge?&&?numEdge?0)
cout?<“輸入有誤!,重新輸入?“;
int?i?j?w;
if?(!isWeighted)??//無權圖
{
cout?<“輸入每條邊的起點和終點:\n“;
for?(int?k?=?0;?k? {
cin?>>?i?>>?j;
while?(!check(i?j))
{
cout?<“輸入的邊不對!重新輸入\n“;
cin?>>?i?>>?j;
}
insertEdge(i?j);
}
}
else??//有權圖
{
cout?<“輸入每條邊的起點、終點和權值:\n“;
for?(int?k?=?0;?k? {
cin?>>?i?>>?j?>>?w;
while?(!check(i?j?w))
{
cout?<“輸入的邊不對!重新輸入\n“;
cin?>>?i?>>?j?>>?w;
}
insertEdge(i?j?w);
}
}
}
//析構方法
Graph::~Graph()
{
int?i;
EdgeNode?*p?*q;
for?(i?=?0;?i? {
if?(adjList[i].next)
{
p?=?adjList[i].next;
while?(p)
{
q?=?p->next;
delete?p;
p?=?q;
}
}
}
delete[]adjList;
}
//設置指定邊的權值
void?Graph::setEdgeWeight(int?tail?int?head?int?weight)
{
if?(!isWeighted)??//無權圖
{
while?(!check(tail?head))
{
cout?<“輸入的邊不對!重新輸入\n“;
cin?>>?tail?>>?head;
}
insertEdge(tail?head);
}
e
- 上一篇:c語言實現獲取文件的md5哈希值
- 下一篇:圖:FLoyd算法
評論
共有 條評論