图的邻接表内容梳理

1.DFS深度优先遍历

template
void ALGraph::DFSTraverse(int v)
{
	ArcNode* p; int j;
	cout << adjlist[v].vertex << " "; p = adjlist[v].firstedge; visited[v] = 1;
	while (p)
	{
		j = p->adjvex;
		if (visited[j] == 0)DFSTraverse(j);
		p = p->next;
	}
}

2.BFS广度优先遍历

template
void ALGraph::BFSTraverse(int v)
{
	ArcNode* p; int j; CirQueue c;
	cout << adjlist[v].vertex << " "; visited[v] = 1; c.EnQueue(v);
	while (c.Empty()==0)
	{
		v = c.DeQueue();
		p= adjlist[v].firstedge;
		while (p)
		{
			j = p->adjvex;
			if (visited[j] == 0)
			{
				cout << adjlist[j].vertex << " ";
				visited[j] = 1;
				c.EnQueue(j);
			}
			p = p->next;
		}
	}
}

3.构造函数

template 
WJYALGraph::WJYALGraph(T a[], int n, int e)
{
	vertexNum = n; arcNum = e;
	for (int i = 0; i < vertexNum; i++)
	{
		adjlist[i].vertex = a[i];
		adjlist[i].firstedge = NULL;
	}
	for (int j = 0; j < arcNum; j++)
	{
		int a, b;
		cin >> a >> b;
		ArcNode* s = new ArcNode; s->adjvex = b;
		s->next = adjlist[a].firstedge;
		adjlist[a].firstedge = s;
		
		s = new ArcNode; s->adjvex = a;
		s->next = adjlist[b].firstedge;
		adjlist[b].firstedge = s;
		
	}
}

注意点:由于构造函数中边表的构造用的是头插法,输出顺序相反。所以在输入边时也以逆序输入。

4.析构函数

template 
ALGraph::~ALGraph( )
{
  for (int i=0; inext;
  delete p;                                                 //释放结点空间
  p=adjlist[i].firstedge;
 }
  }
}

5.主函数

int main()
{
 string a[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N"}; //顶点信息
 int i,n,e;
 cin>>n>>e;  //输入顶点个数和边个数
    ALGraph G(a,n,e);
 G.DispALGraph();
 for(i=0;i

 

你可能感兴趣的:(数据结构,dfs,bfs,图论,c++)