【问题标题】:Create graph using adjacency list使用邻接表创建图
【发布时间】:2010-04-20 05:52:42
【问题描述】:
#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;
}

【问题讨论】:

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


    【解决方案1】:

    你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 的 next 字段:

    newNode = new ListNode;
    newNode->name = vName;
    newNode->next= NULL; // add this.
    

    释放动态分配的内存也是一个好习惯。所以不要有一个空的析构函数

    ~TCSGraph();
    

    您可以在 dtor 中释放列表。

    编辑:更多错误

    你有一个失踪;在类声明之后:

    class TCSGraph{
    ......
    
    }; // <--- add this ;
    

    你的析构函数也只被声明了。没有定义。如果你不想给出任何定义,你至少必须有一个空的身体。所以替换

    ~TCSGraph();
    

    与

    ~TCSGraph(){}
    

    【讨论】:

    • 哦,我的错误>错误:新类型可能未在返回类型中定义>@声明中的两个或多个数据类型987654332@TCSGraph TCSGraph::addVertex(int)' 与 TCSGraph'| &gt;error: candidate is: void TCSGraph::addVertex(int)| &gt;error: TCSGraph TCSGraph::addVertex(int)' 类中的任何内容都不匹配,并且 `void TCSGraph::addVertex(int)' 不能重载
    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多