Create graph using adjacency list

和自甴很熟 提交于 2019-11-30 19:36:02

问题


#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

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