Create graph using adjacency list

走远了吗. 提交于 2019-12-01 00:35:41

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(){}

Have you taken a look at Boost Graph Library and boost::adjacency_list?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!