使用邻接表创建图
#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;
}
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
addvertex
方法有问题:您有:
但应该是:
而且您没有创建
newNode
的next
字段 < code>NULL:释放动态分配的内存也是一个很好的做法。 而不是使用空的析构函数
因此,您可以释放 dtor 中的列表,
。 编辑:更多错误
您缺少 ;在类声明之后:
您的析构函数也仅被声明。没有定义。如果你不想给任何def,你至少得有一个空的身体。所以替换
为
There is a problem in you
addvertex
method:You have:
but it should be:
Also you are not making the
next
field of thenewNode
NULL
:Also its a good practice to free up the dynamically allocated memory. So instead of having an empty destructor
you can free up the list in the dtor.
EDIT: More bugs
You have a missing ; after the class declaration:
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
with
您看过Boost Graph Library 和
boost::adjacency_list
?Have you taken a look at Boost Graph Library and
boost::adjacency_list
?