#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;
}
最佳答案
addvertex
方法有问题:
你有:
if (!head)
head = newNode;
else
nodePtr = head;
while(nodePtr->next)
nodePtr = nodePtr->next;
nodePtr->next = newNode;
但它应该是:
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.
}
此外,您还没有创建 newNode
NULL
的 next
字段:
newNode = new ListNode;
newNode->name = vName;
newNode->next= NULL; // add this.
释放动态分配的内存也是一个好习惯。所以不要有一个空的析构函数
~TCSGraph();
您可以释放 dtor 中的列表。
编辑:更多错误
你有一个失踪;类声明之后:
class TCSGraph{
......
}; // <--- add this ;
此外,您的析构函数仅被声明。没有定义。如果你不想给任何def,你至少必须有一个空的 body 。所以替换
~TCSGraph();
与
~TCSGraph(){}
关于c++ - 使用邻接表创建图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2672866/