十字链表方式存储图:
十字链表的节点结构:节点+前驱节点链表+后继节点链表
十字链表的边结构:头节点+尾节点+尾节点的前驱节点链表+头节点的后继节点链表.
对于如下图结构:
转换为十字链表:
十字链表和链表存储图的比较:
1.存储空间上十字链表比链表要多.
2.从效率上,十字链表可以直接查询节点的前驱和后继节点.
典型的以空间换时间.不过消耗的空间很少.
执行结果:
#include<iostream>
usingnamespace std;
typedefchar VextexType;
typedefint EdgeType;
#defineVexNum 5
structEdgeNode;
structEdgeNode {
VextexType HeadName;
VextexType TailName;
EdgeType weight;
EdgeNode *VexOut;
EdgeNode *VexIn;
};
typedefstruct
{
VextexType name;
EdgeNode *VexOutlink;
EdgeNode *VexInlink;
}VexNode;
VexNodeadjList[VexNum];
voidcreatGraph()
{
VextexType vextemp;
EdgeType edgetemp;
//input n vextex
for ( int i=0; i<VexNum ; ++i ){
cin>>vextemp;
adjList[i].name = vextemp;
adjList[i].VexOutlink = NULL;
adjList[i].VexInlink = NULL;
}
for ( int i=0; i<VexNum*VexNum; ++i ){
cin>>edgetemp;
if ( edgetemp==0 ){
continue;
}
EdgeNode *pEdge = new EdgeNode;
pEdge->HeadName =adjList[i/VexNum].name;
pEdge->TailName =adjList[i%VexNum].name;
pEdge->weight = edgetemp;
pEdge->VexOut = adjList[i/VexNum].VexOutlink;
if ( pEdge->VexOut ){
while ( pEdge->VexOut->VexOut){
pEdge->VexOut=pEdge->VexOut->VexOut;
}
pEdge->VexOut->VexOut =pEdge;
pEdge->VexOut=NULL;
} else {
adjList[i/VexNum].VexOutlink =pEdge;
pEdge->VexOut = NULL;
}
}
for ( inti=0 ;i<VexNum ;++i ){
EdgeNode **pInLink =&adjList[i].VexInlink;
for ( int j=0; j<VexNum; ++j ){
if ( i==j ){
continue;
}
EdgeNode *p = adjList[j].VexOutlink;
while ( p ){
if ( p->TailName !=adjList[i].name ){
p = p->VexOut;
continue;
}
*pInLink = p;
pInLink = &p->VexIn;
p = p->VexOut;
}
}
*pInLink = NULL;
}
}
voiddestroyGrape()
{
for ( int i=0; i<VexNum ;++i ){
EdgeNode *p = adjList[i].VexOutlink;
EdgeNode *q;
while ( p ){
q = p;
p = p->VexOut;
delete q;
}
}
}
voidprintGrape()
{
for ( int i=0; i<VexNum; ++i ){
cout<<adjList[i].name<<"-->";
EdgeNode *p = adjList[i].VexOutlink;
while ( p ){
cout<<"("<<p->HeadName<<","<<p->TailName<<","<<p->weight<<")";
p = p->VexOut;
}
cout<<endl;
p = adjList[i].VexInlink;
cout<<adjList[i].name<<"-->";
while ( p ){
cout<<"("<<p->HeadName<<","<<p->TailName<<","<<p->weight<<")";
p = p->VexIn;
}
cout<<endl;
}
}
int main()
{
creatGraph();
printGrape();
destroyGrape();
}