coolComputer 2016-12-02 01:27 采纳率: 12.5%
浏览 1103
已结题

C++图的深度优先遍历非递归哪里错了?

#include
using namespace std;
const int MaxSize=10;
int visited[MaxSize]= {0};
struct ArcNode {
int adjvex;
ArcNode *next;
};
template
struct VertexNode {
DataType vertex;
ArcNode *firstedge;

};
template
class ALGraph {
public:
ALGraph(DataType a[],int n,int e);
~ALGraph();
void DFSTraverse(int v);
void BFSTraverse(int v);
private:
VertexNode adjlist[MaxSize];
int vertexNum,arcNum;
} ;
template
ALGraph::ALGraph(DataType a[],int n,int e) {
vertexNum=n;
arcNum=e;
for(int i=0; i adjlist[i].vertex=a[i];
adjlist[i].firstedge=NULL;
}
for(int k=0; k int i,j;
cin>>i>>j;
ArcNode *s=new ArcNode;
s->adjvex=j;
s->next=adjlist[i].firstedge;
adjlist[i].firstedge=s;
}

}
template
ALGraph::~ALGraph() {
for(int i=0; i if(adjlist[i].firstedge!=NULL) {
ArcNode *p,*q;
p=adjlist[i].firstedge;
while(p!=NULL) {
q=p;
p=p->next;
delete q;
}
}
}
}
template
void ALGraph::DFSTraverse(int v) {
int visited[100]= {0};
int Q[100];
int top=-1;
ArcNode p;
cout< Q[++top]=v;
visited[v]=1;
while(top!=-1) {
v=Q[top--];
p=adjlist[v].firstedge;
while(p!=NULL) {
if(visited[p->adjvex]==0) {
visited[p->adjvex]=1;
cout<adjvex].vertex<<" ";
Q[++top]=adjlist[p->adjvex].vertex;
p=adjlist[p->adjvex].firstedge;
} else {
p=p->next;
}
}
if(p==NULL) {
v=Q[--top];
//p=adjlist[v].firstedge;
}
}
}
template
void ALGraph::BFSTraverse(int v) {
int visited[MaxSize]= {0};
int Q[MaxSize];
int front=-1,rear=-1;
cout< visited[v]=1;
Q[++rear]=v;
while(front!=rear) {
ArcNode *p;
int j;
v=Q[++front];
p=adjlist[v].firstedge;
while(p!=NULL) {
j=p->adjvex;
if(visited[j]==0) {
cout< visited[j]=1;
Q[++rear]=j;
}
p=p->next;
}
}
}
int main() {
int n=4,e=4;
char a[4]= {'a','b','c','d'};
ALGraph example(a,n,e);
cout<<"Depth-first-Traverse:";
example.DFSTraverse(0);
/*cout<<"Breath-first-Traverse:";
example.BFSTraverse(0);
/
return 0;
}

  • 写回答

1条回答 默认 最新

  • shen_wei 2016-12-02 03:17
    关注

    图片说明

    请这样粘贴代码。。不然你的for循环就错误了。。。

    评论

报告相同问题?

悬赏问题

  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥20 Python安装cvxpy库出问题
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题