问题
#include<iostream>
using namespace std;
class TCSGraph{
public:
void addVertex(int vertex);
void display();
TCSGraph(){
head = NULL;
}
~TCSGraph();
private:
struct ListNode
{
string name;
struct ListNode *next;
};
ListNode *head;
}
void TCSGraph::addVertex(int vertex){
ListNode *newNode;
ListNode *nodePtr;
string vName;
for(int i = 0; i < vertex ; i++ ){
cout << "what is the name of the vertex"<< endl;
cin >> vName;
newNode = new ListNode;
newNode->name = vName;
if (!head)
head = newNode;
else
nodePtr = head;
while(nodePtr->next)
nodePtr = nodePtr->next;
nodePtr->next = newNode;
}
}
void TCSGraph::display(){
ListNode *nodePtr;
nodePtr = head;
while(nodePtr){
cout << nodePtr->name<< endl;
nodePtr = nodePtr->next;
}
}
int main(){
int vertex;
cout << " how many vertex u wan to add" << endl;
cin >> vertex;
TCSGraph g;
g.addVertex(vertex);
g.display();
return 0;
}
回答1:
There is a problem in you addvertex
method:
You have:
if (!head)
head = newNode;
else
nodePtr = head;
while(nodePtr->next)
nodePtr = nodePtr->next;
nodePtr->next = newNode;
but it should be:
if (!head) // check if the list is empty.
head = newNode;// if yes..make the new node the first node.
else { // list exits.
nodePtr = head;
while(nodePtr->next) // keep moving till the end of the list.
nodePtr = nodePtr->next;
nodePtr->next = newNode; // add new node to the end.
}
Also you are not making the next
field of the newNode
NULL
:
newNode = new ListNode;
newNode->name = vName;
newNode->next= NULL; // add this.
Also its a good practice to free up the dynamically allocated memory. So instead of having an empty destructor
~TCSGraph();
you can free up the list in the dtor.
EDIT: More bugs
You have a missing ; after the class declaration:
class TCSGraph{
......
}; // <--- add this ;
Also your destructor is only declared. There is no def. If you don't want to give any def, you must at least have a empty body. So replace
~TCSGraph();
with
~TCSGraph(){}
回答2:
Have you taken a look at Boost Graph Library and boost::adjacency_list?
来源:https://stackoverflow.com/questions/2672866/create-graph-using-adjacency-list