邻接矩阵实现:
运用了链式结构,其中包括一条用来存储起始节点的链表(纵向),另外一条用来存储与特定的起始点直接相邻的邻接点(横向);有待改进的是对于横向结构链表的存储存在头结点的冗余,因为在纵向结构中为了将其连接起来也为其设置了头结点。
代码如下:
#include <iostream>
#include <string.h>
using namespace std;
#define WHITE -1;
#define GRAY 0;
#define BLACK 1;
class Topoint
{
public:
string topointname;
int topointweight;
int topointcolor;
Topoint* nexto;
Topoint()
{
nexto=NULL;
}
Topoint(string _topointname,int _topointweight,int _topointcolor)
{
topointname=_topointname;
topointweight=_topointweight;
topointcolor=_topointcolor;
nexto=NULL;
}
void Display()
{
cout<<"ToPoint name: "<<topointname<<" weight: "<<topointweight<<" pointcolor: "<<topointcolor<<endl;
}
};
class Frompoint
{
public:
string frompointname;
int frompointcolor;
Frompoint* nextpoint;
Topoint* nextopoint;
Frompoint()
{
nextpoint=NULL;
nextopoint=NULL;
}
Frompoint(string _frompointname,int _frompointcolor)
{
frompointname=_frompointname;
frompointcolor=_frompointcolor;
nextopoint=NULL;
nextpoint=NULL;
}
void Display()
{
cout<<"Frompoint name: "<<frompointname<<" pointcolor: "<<frompointcolor<<endl;
}
};
class Topointlinklist
{
public:
Topoint* head;
Topoint* rear;
Topointlinklist()
{
head=NULL;
rear=NULL;
}
int InsertTopoint(string topointname,int topointweight,int topointcolor)
{
Topoint* p=new Topoint(topointname,topointweight,topointcolor);
if(head==NULL)
{
head=rear=p;
return 1;
}
else
{
rear->nexto=p;
rear=rear->nexto;
return 1;
}
return 0;
}
void Display()
{
Topoint* p=head;
cout<<"横向遍历:"<<endl;
while(p!=NULL)
{
p->Display();
p=p->nexto;
}
}
};
class Headlinklist
{
public:
Frompoint* head;
Frompoint* rear;
Headlinklist()
{
head=NULL;
rear=NULL;
}
int InsertFrompoint(string frompointname,int frompointcolor) //竖直方向添加节点
{
Frompoint* p=new Frompoint(frompointname,frompointcolor);
if(head==NULL)
{
head=rear=p;
return 1;
}
else
{
rear->nextpoint=p;
rear=rear->nextpoint;
return 1;
}
return 0;
}
void InsertTopointList(Topointlinklist t)
{
rear->nextopoint=t.head;
}
void Display()
{
Frompoint* p=head;
cout<<"纵向遍历起始节点:"<<endl;
while(p!=NULL)
{
p->Display();
p=p->nextpoint;
}
}
};
int main()
{
Headlinklist head1;
Topointlinklist list1;
head1.InsertFrompoint("1",-1);
list1.InsertTopoint("1",1,-1);
list1.InsertTopoint("2",1,-1);
list1.InsertTopoint("3",1,-1);
head1.InsertTopointList(list1);
Topointlinklist list2;
head1.InsertFrompoint("2",-1);
list2.InsertTopoint("2",1,-1);
list2.InsertTopoint("3",1,-1);
list2.InsertTopoint("4",1,-1);
head1.InsertTopointList(list2);
list1.Display();
list2.Display();
head1.Display();
}