c++ - 使用邻接表创建图

标签 c++ data-structures graph adjacency-list

#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 NULLnext 字段:

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/

相关文章:

C++ 初始化指针随机崩溃应用程序?

C++11 升级技术

java - 生成 2 个地理点之间的可能路径

c++ - 从第二次调用开始执行函数中的一段代码

c++ - 性能与 C++ 内存模型

sql - 复杂分组 - 设计/性能问题

swift - 如何在 Swift 中实现管理 UserDefaults 的键值对的通用结构?

algorithm - 我在哪里可以学习如何结合算法和数据结构?

python - 如何访问图形工具边缘?为什么图形工具边没有 id?

javascript - 有向无环图中所有 Node 的可达性计数