数据结构-图
最近正在看算法4,代码是Java的,打算将其转化成C++,今晚看的是图,看得很少。
一点一点完善
今晚先写了个读取文件的构图的
#include<iostream> #include<fstream> using namespace std; const int MAX=10000; struct Node{ int name;//点的名字 Node *next; }; class Head { public: int name; Node *next; Head() { this->name = -1; this->next = NULL; } }; class Graph { private: int V;//点的数量 int E;//边的数量 public: Head head[MAX]; int getV() { return this->V; } int getE() { return this->E; } Graph(ifstream &ss) {//坑:这里要使用引用传递(错误提示:该函数已删除)//ss是一个一个数读的 ifstream s; ss >> this->V; ss >> this->E; for (int i = 0;i < E;i++) { int index; ss >> index; Node * node = new Node;//新建节点。 Node *node1 = new Node; ss >> node->name;
//这个过程大概就是,读取到一个节点后,就去相应的head位置。实现相互插入。 head[index].name = index; node->next = head[index].next; head[index].next = node; head[node->name].name= node->name; node1->next = head[node->name].next; node1->name = head[index].name; head[node->name].next = node1; } }
~Graph(){} void display() { for (int i = 0;i < V;i++) { cout << head[i].name << "->"; Node *node = head[i].next; while (node->next!= NULL) { cout << node->name; if (node->name < head[i].name) cout << "!";//如果后面出现有节点比头结点的数字小,那么之前肯定出现过,原文中是设置成红色,我这里是输出一个感叹号。 cout << "->"; node = node->next; } if (node->name < head[i].name) cout << "!"; cout << node->name << endl; } } }; int main() { ifstream ss("D:\\1.txt"); Graph G(ss); G.display(); cin.get(); }
测试用例
13//点的个数
13//边的条数
0 5
4 3
0 1
9 12
6 4
5 4
0 2
11 12
9 10
0 6
7 8
9 11
5 3
和书本的一样

输出结果:(左) 书本的结果:



浙公网安备 33010602011771号