当前位置:   article > 正文

邻接表实现拓扑排序_第2关:基于邻接表完成拓扑排序

第2关:基于邻接表完成拓扑排序
  1. #include <iostream>
  2. #include <stack>
  3. using namespace std;
  4. struct node {
  5. int index;
  6. node* next;
  7. node() { next = NULL; }
  8. node(int i) { index = i; next = NULL; }
  9. };
  10. struct head {
  11. int in;
  12. char data;
  13. node* adj;
  14. head() { in = 0; }
  15. };
  16. head h[100];
  17. int vexnum;
  18. stack<int> s;
  19. void topology() {
  20. //初始化栈
  21. for (int i = 1; i <= vexnum; i++) {
  22. if (h[i].in == 0) {
  23. s.push(i);//是0,就把节点压入
  24. }
  25. }
  26. while (!s.empty()) {
  27. int i = s.top();
  28. s.pop();
  29. cout << h[i].data << " ";
  30. node* p = h[i].adj;
  31. while (p != NULL) {
  32. int ii = p->index;
  33. h[ii].in--;
  34. if (h[ii].in == 0) {
  35. s.push(ii);
  36. }
  37. p = p->next;
  38. }
  39. }
  40. }
  41. int findnode(char c) {
  42. for (int i = 1; i <= vexnum; i++) {
  43. if (c == h[i].data)
  44. return i;
  45. }
  46. return -1;
  47. }
  48. void create() {
  49. cout << "请输入节点信息" << endl;
  50. for (int i = 1; i <= vexnum; i++) {
  51. cin>>h[i].data;
  52. }
  53. cout << "请问有几条边" << endl;
  54. int line;
  55. cin >> line;
  56. cout << "请输入拓扑信息" << endl;
  57. for (int i = 0; i < line; i++) {
  58. char a, b;
  59. cin >> a >> b;
  60. int ai = findnode(a);
  61. int bi = findnode(b);
  62. node* p = new node(bi);
  63. p->next = h[ai].adj;
  64. h[ai].adj = p;
  65. h[bi].in++;
  66. }
  67. }
  68. int main() {
  69. cout << "请问有几个顶点" << endl;
  70. cin >> vexnum;
  71. create();
  72. //打印创建的邻接表
  73. /*for (int i = 1; i <= vexnum; i++) {
  74. cout << h[i].data << " "<<h[i].in<<" ";
  75. node* p = h[i].adj;
  76. while (p != NULL) {
  77. cout << p->index << " ";
  78. p = p->next;
  79. }
  80. cout << endl;
  81. }*/
  82. topology();
  83. return 0;
  84. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/870803
推荐阅读
相关标签
  

闽ICP备14008679号