《数据结构》实验六-----邻接表

前端之家收集整理的这篇文章主要介绍了《数据结构》实验六-----邻接表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

图的逻辑结构如下:


代码

文件ALGraph.h:

  1. #ifndef ALGraph_H
  2. #define ALGraoh_H
  3. #include<stdlib.h>
  4. const int N = 10;
  5. int visited[N] {0};
  6. struct Arcnode
  7. {
  8. int adjvex;
  9. Arcnode *next;
  10. };
  11. template<class T>
  12. struct Vertexnode
  13. {
  14. T vertex;
  15. Arcnode *firstedge;
  16. };
  17. template<typename T>
  18. class ALGraph
  19. {
  20. public:
  21. ALGraph(T a[],int num,int edge);
  22. ~ALGraph()
  23. {
  24. system("pause");
  25. }
  26. void BFS(int v);
  27. void DFS(int v);
  28. private:
  29. Vertexnode<T> adjlist[N];
  30. int vertexnum,arcnum;
  31. };
  32. template<class T>
  33. ALGraph<T>::ALGraph(T a[],int edge)
  34. {
  35. Arcnode *s;
  36. int i,j,k;
  37. vertexnum = num;
  38. arcnum = edge;
  39. for (i = 0; i < vertexnum; i++)
  40. {
  41. adjlist[i].vertex = a[i];
  42. adjlist[i].firstedge = NULL;
  43. }
  44. for (k = 0; k < arcnum; k++)
  45. {
  46. cout << "请输入两个相连顶点的编号:";
  47. cin >> i;
  48. cin >> j;
  49. s = new Arcnode;
  50. s->adjvex = j;
  51. s->next = adjlist[i].firstedge;
  52. adjlist[i].firstedge = s;
  53. }
  54. }
  55. template<class T>
  56. void ALGraph<T>::BFS(int v)
  57. {
  58. Arcnode *p = nullptr;
  59. int Q[N];
  60. int front,rear;
  61. front = -1; rear = -1;
  62. cout << adjlist[v].vertex;
  63. Q[++rear] = v;
  64. while (front!=rear)
  65. {
  66. v = Q[++front];
  67. p = adjlist[v].firstedge;
  68. while (p != nullptr)
  69. {
  70. int j;
  71. j = p->adjvex;
  72. if (visited[j] == 0)
  73. {
  74. cout << adjlist[j].vertex;
  75. visited[j] = 1;
  76. Q[++rear] = j;
  77. }
  78. p = p->next;
  79. }
  80. }
  81. }
  82. template<class T>
  83. void ALGraph<T>::DFS(int v)
  84. {
  85. Arcnode *p = nullptr;
  86. int j;
  87. cout << adjlist[v].vertex;
  88. visited[v] = 1;
  89. p = adjlist[v].firstedge;
  90. while (p != nullptr)
  91. {
  92. j = p->adjvex;
  93. if (visited[j] == 0)
  94. DFS(j);
  95. p = p->next;
  96. }
  97. }
  98.  
  99. template<class T>
  100. void showBFS(ALGraph<T> ALG)
  101. {
  102. cout << "广度优先遍历结果为:";
  103. ALG.BFS(0);
  104. cout << endl;
  105. }
  106. template<class T>
  107. void showDFS(ALGraph<T> ALG_0)
  108. {
  109. cout << "深度优先遍历结果为:";
  110. ALG_0.DFS(0);
  111. cout << endl;
  112. }
  113. #endif

文件ALGraph_main.cpp:

  1. #include<iostream>
  2. #include"ALGraph.h"
  3. using namespace std;
  4. int main()
  5. {
  6. char S[] {'A','B','C','D','E','F'};
  7. int i;
  8. ALGraph<char> G(S,6,6);
  9. for (i = 0; i < N; i++)
  10. visited[i]=0;
  11. showBFS(G);
  12. for (i = 0; i < N; i++)
  13. visited[i] = 0;
  14. showDFS(G);
  15. cout << endl;
  16. return 0;
  17. }

运行截图:

猜你在找的数据结构相关文章