前几天我写了这个问题:See here
我在哪里询问如何在图结构中的列表中插入元素。 我一直在编写更多代码,并且达到了我无法前进的地步。
我发布的代码只是为了让你有个主意:
//data_structures.h
#include <list>
// A structure to represent an adjacency list node
struct AdjListNode
{
int dest;
int weight;
std::list<int> adjacents;
struct AdjListNode* next;
AdjListNode() : dest(0), weight(0), next(NULL) {}
};
// A structure to represent an adjacency list
struct AdjList
{
struct AdjListNode *head; // pointer to head node of list
//Initialize each adjacency list as empty by making head as NULL
AdjList(): head(NULL) {}
~AdjList()
{
while (head) {
struct AdjListNode* temp = head;
head = head->next;
delete temp;
}
}
void addAdjacent(int adjacent) {
struct AdjListNode* newNode = new AdjListNode;
newNode->next = head;
head = newNode;
newNode->adjacents.push_back(adjacent);
}
};
// A structure to represent a graph. A graph is an array of adjacency lists.
// Size of array will be V (number of vertices in graph)
struct Graph
{
int V;
struct AdjList* array;
// Create an array of adjacency lists. Size of array will be V
Graph(int v) : V(v), array(NULL) {
if(v >= 0) {
array = new struct AdjList[v];
}
else {
throw std::bad_alloc();
}
}
~Graph() {delete [] array;}
};
//main.cpp
int main()
{
// create the graph given in above figure
struct Graph* graph = new Graph(2);
graph->array[0].addAdjacent(1);
graph->array[1].addAdjacent(0);
for(int i = 0; i < graph->V; i++) {
for (list<int>::iterator it = graph->array[i].head->adjacents.begin();
it != graph->array[i].head->adjacents.end(); ++it) {
cout << "Vertex: " << i << " is adjacent to: " << *it << endl;
cout << "Amount: " << graph->array[i].head->adjacents.size() << endl;
cout << endl;
}
}
return 0;
}
由于图形是无向的,零时的输出连接到1,反之亦然(graph-&gt; array [0] .addAdjacent(1); array 1。addAdjacent(0);)is :
顶点:0与:1相邻 顶点:1与:0
相邻然而,添加更多顶点(比如说只有一个)连接到顶点0,例如:
改变这个:
graph->array[0].addAdjacent(1);
graph->array[1].addAdjacent(0);
通过
graph->array[0].addAdjacent(1);
graph->array[1].addAdjacent(0);
graph->array[0].addAdjacent(2);
graph->array[2].addAdjacent(0);
会输出:
顶点:0与:2
相邻顶点:1与0相邻:
顶点:2与:0
相邻显然不正确。就像顶点0被覆盖一样。有什么帮助吗?