} edge* e = adj[u].head; while (e != nullptr) { if (!visited[e->dest]) { visited[e->dest] = true; q.push(e->dest); } e = e->next; } } } }; int main() { int V, E; cout << "请输入顶点数和边数:" << endl; cin >> V >> E; Graph g(V); cout << "请输入每条边的起点和终点:" << endl; for (int i = 0; i < E; ++i) { char src, dest; cin >> src >> dest; g.addEdge(src, dest); } // 深度优先遍历 cout << "深度优先遍历结果为:" << endl; bool* visited = new bool[V]; for (int i = 0; i < V; ++i) { visited[i] = false; } for (int i = 0; i < V; ++i) { if (!visited[i]) { g.DFS(i, visited); } } cout << endl; // 广度优先遍历 cout << "广度优先遍历结果为:" << endl; for (int i = 0; i < V; ++i) { visited[i] = false; } for (int i = 0; i < V; ++i) { if (!visited[i]) { g.BFS(i, visited); } } cout << endl; return 0; }成员变量head和numVertices在哪段里
时间: 2024-02-10 10:10:52 浏览: 116
在给出的代码中,head和numVertices是Graph类的私有成员变量,位于类定义中的以下部分:
```c++
class Graph {
private:
struct edge {
int dest;
edge* next;
};
struct vertex {
edge* head;
};
vertex* vertices;
int numVertices;
public:
Graph(int n) {
vertices = new vertex[n];
numVertices = n;
for (int i = 0; i < numVertices; ++i) {
vertices[i].head = nullptr;
}
}
void addEdge(int src, int dest) {
edge* e = new edge;
e->dest = dest;
e->next = vertices[src].head;
vertices[src].head = e;
}
void DFS(int u, bool* visited) {
visited[u] = true;
cout << u << " ";
edge* e = vertices[u].head;
while (e != nullptr) {
if (!visited[e->dest]) {
DFS(e->dest, visited);
}
e = e->next;
}
}
void BFS(int u, bool* visited) {
queue<int> q;
visited[u] = true;
q.push(u);
while (!q.empty()) {
u = q.front();
q.pop();
cout << u << " ";
edge* e = vertices[u].head;
while (e != nullptr) {
if (!visited[e->dest]) {
visited[e->dest] = true;
q.push(e->dest);
}
e = e->next;
}
}
}
};
```
其中,head是每个顶点的链表头指针,用于存储与该顶点相邻的边;numVertices表示图中顶点的数量。
阅读全文