2
#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;
}
4

2 に答える 2

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 NULL

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

また、動的に割り当てられたメモリを解放することもお勧めします。したがって、空のデストラクタを使用する代わりに

~TCSGraph();

dtorでリストを解放できます。

編集:より多くのバグ

あなたには行方不明があります; クラス宣言後:

class TCSGraph{
......

}; // <--- add this ;

また、デストラクタは宣言されるだけです。defはありません。defを与えたくない場合は、少なくとも空のボディが必要です。だから交換する

~TCSGraph();

~TCSGraph(){}
于 2010-04-20T05:57:25.450 に答える
0

Boost Graph Libraryをご覧になりましたboost::adjacency_listか?

于 2010-04-20T06:25:09.127 に答える