使用邻接列表创建图形

时间:2010-04-20 05:52:42

标签: 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;
}

2 个答案:

答案 0 :(得分:2)

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.
}

此外,您还没有next newNode的{​​{1}}字段:

NULL

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

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

你可以释放dtor中的列表。

编辑:更多错误

你失踪了;在课堂宣言之后:

~TCSGraph();

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

class TCSGraph{
......

}; // <--- add this ;

~TCSGraph();

答案 1 :(得分:0)