使用邻接列表创建图 [英] Create graph using adjacency list

查看:176
本文介绍了使用邻接列表创建图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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

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();

您可以释放dtor中的列表。

you can free up the list in the dtor.

编辑:更多错误

你缺少;课后申报:

class TCSGraph{
......

}; // <--- add this ;

您的析构函数只会声明。没有def如果你不想给任何def,你必须至少有一个空的身体。所以替换

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();

~TCSGraph(){}

这篇关于使用邻接列表创建图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆