图的邻接表表示方法采用链表的方式针对每个节点创建一个属于自己的链表,其中头指针为节点自身,其后的所有元素为与自己相连的其他节点,头结点只需记录节点的名字和序号,链表的其他节点还需记录两点之间边的权值,本文实现了其插入、创建、打印等方法,以下为该类的C++实现代码。
//graphlinkedtable.h
#ifndef GraphLinkedTable_H
#define GraphLinkedTable_H
#include <IOSTREAM>
struct adjNode{
int name;
int weight;
adjNode* next;
};
struct VNode{
int name;
adjNode* next;
};
const int MaxVertexCount=100;
class GraphLinkedTable{
private:
VNode VERTEX[MaxVertexCount];
int VertexCount;
int EdgeCount;
public:
GraphLinkedTable();
~GraphLinkedTable(){}
void InsertEdge(int v1,int v2,int w);
void BuildGraph();
void Print();
};
GraphLinkedTable::GraphLinkedTable()
{
VertexCount=0;
EdgeCount=0;
for(int i=0;i<MaxVertexCount;i++)
{
VERTEX[i].name=-1;
VERTEX[i].next=NULL;
}
}
void GraphLinkedTable::InsertEdge(int v1,int v2,int w)
{
adjNode* end=new adjNode;
end->name=v2;
end->weight=w;
end->next=NULL;
adjNode* temp=VERTEX[v1].next;
if(!temp)
{
VERTEX[v1].next=end;
return;
}
adjNode* tempbefore=temp;
while(temp)
{
tempbefore=temp;
temp=temp->next;
}
tempbefore->next=end;
}
void GraphLinkedTable::BuildGraph()
{
std::cout<<"Please input the nodes number of the graph:"<<std::endl;
std::cin>>VertexCount;
std::cout<<"Please input the edges number of the graph:"<<std::endl;
std::cin>>EdgeCount;
std::cout<<"Please input the edges one by one, just like (1 2 5)"<<std::endl;
for(int i=0;i<EdgeCount;i++)
{
int a,b,c;
std::cin>>a>>b>>c;
InsertEdge(a-1,b-1,c);
}
}
void GraphLinkedTable::Print()
{
for(int i=0;i<VertexCount;i++)
{
std::cout<<VERTEX[i].name<<" ";
adjNode* temp=VERTEX[i].next;
while(temp)
{
std::cout<<temp->weight<<" ";
std::cout<<temp->name<<" ";
temp=temp->next;
}
std::cout<<std::endl;
}
}
#endif