摘自计蒜客:http://www.jisuanke.com/course/35/7198
//使用现成的链表类,构造出一个图的邻接表结构
//首先,我们来定义Graph类的成员,邻接表需要保存每个顶点相邻的所有边的信息,就像下图中的例子:
用邻接表保存的结果为:
也就是对于每个顶点,需要用一个链表来保存,因此一共需要和顶点数量一样多的链表。
#include <iostream>
using namespace std;
class LinkedListNode {
public:
int vertex;
LinkedListNode *next;
LinkedListNode(int vertex_input) {
vertex = vertex_input;
next = NULL;
}
};
class LinkedList {
public:
LinkedListNode *head;
LinkedList() {
head = NULL;
}
~LinkedList() {
while (head != NULL) {
LinkedListNode *delete_node = head;
head = head->next;
delete delete_node;
}
}
void insert(int vertex) {
LinkedListNode *node = new LinkedListNode(vertex);
node->next = head;
head = node;
}
};
class Graph {
private:
LinkedList *edges;
int n;
public:
Graph(int input_n) {
n = input_n;
edges = new LinkedList[n];
}
~Graph() {
delete[] edges;
}
//插入一条从x连向y的边,将y的值插入到x对应的链表中。
void insert(int x, int y) {
edges[x].insert(y);
}
void output() {
for(int i=0; i<n; i++) {
cout << i << ":";
for(auto j = edges[i].head; j != NULL; j = j->next) {
cout << j->vertex << " ";
}
cout << endl;
}
}
};
int main() {
int n, m, x, y;
cin >> n >> m;
Graph g(n);
for (int i = 0; i < m; ++i) {
cin >> x >> y;
g.insert(x, y);
}
g.output();
return 0;
}