29.有向图邻接表类
namespace DSList
{
//有向图邻接表类(Directed Graph Adjacency List Class)
public class DireGraAdjList<T> : IDireGraph<T>
{
private ALVexNode<T>[] adjList;
public ALVexNode<T> this[int index]
{
get
{
return adjList[index];
}
set
{
adjList[index] = value;
}
}
public DireGraAdjList(GvNode<T>[] nodes)
{
adjList = new ALVexNode<T>[nodes.Length];
for (int i = 0; i < nodes.Length; ++i)
{
adjList[i] = new ALVexNode<T>(nodes[i]);
}
}
public int GetNumOfVertex()
{
return adjList.Length;
}
public int GetNumOfArc()
{
int i = 0;
foreach (ALVexNode<T> nd in adjList)
{
AdjListNode<T> p = nd.FirstAdj;
while (p != null)
{
++i;
p = p.Next;
}
}
return i;
}
public bool IsGvNode(GvNode<T> v)
{
foreach (ALVexNode<T> nd in adjList)
{
if (nd.Data.Equals(v))
{
return true;
}
}
return false;
}
public int GetIndex(GvNode<T> v)
{
int i = -1;
for (i = 0; i < adjList.Length; ++i)
{
if (adjList[i].Data.Equals(v))
{
return i;
}
}
return i;
}
public void SetArc(GvNode<T> v1, GvNode<T> v2, int v)
{
if (!IsGvNode(v1) || !IsGvNode(v2))
{
Console.WriteLine("GvNode is not belong to Graph!");
return;
}
if (v == 1)
{
AdjListNode<T> p = new AdjListNode<T>(GetIndex(v2));
if (adjList[GetIndex(v1)].FirstAdj == null)
{
adjList[GetIndex(v1)].FirstAdj = p;
p.Weight = v;
}
else
{
p.Next = adjList[GetIndex(v1)].FirstAdj;
adjList[GetIndex(v1)].FirstAdj = p;
p.Weight = v;
}
}
else
{
Console.WriteLine("Weight is not right!");
return;
}
}
public void DelArc(GvNode<T> v1, GvNode<T> v2)
{
if (!IsGvNode(v1) || !IsGvNode(v2))
{
Console.WriteLine("GvNode is not belong to Graph!");
return;
}
if (IsArc(v1, v2) == true)
{
AdjListNode<T> p = adjList[GetIndex(v1)].FirstAdj;
AdjListNode<T> pre = null;
while (p != null && p.AdjVex != GetIndex(v2))
{
pre = p;
p = p.Next;
}
pre.Next = p.Next;
}
else
{
Console.WriteLine("Arc is not existent!");
return;
}
}
public bool IsArc(GvNode<T> v1, GvNode<T> v2)
{
if (!IsGvNode(v1) || !IsGvNode(v2))
{
Console.WriteLine("GvNode is not belong to Graph!");
return false;
}
AdjListNode<T> p = adjList[GetIndex(v1)].FirstAdj;
while (p != null)
{
if (p.AdjVex == GetIndex(v2))
{
return true;
}
p = p.Next;
}
return false;
}
}
}