views:

301

answers:

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;
}
+1  A: 

There is a problem in you addvertex method:

You have:

if (!head) 
    head = newNode; 
else
nodePtr = head;
while(nodePtr->next)
nodePtr = nodePtr->next;
nodePtr->next = newNode;

but it should be:

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

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

you can free up the list in the dtor.

EDIT: More bugs

You have a missing ; after the class declaration:

class TCSGraph{
......

}; // <--- add this ;

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

with

~TCSGraph(){}
codaddict
oh my mistakes ><but it still the same error i facing here are those error messages: >error: new types may not be defined in a return type >two or more data types in declaration of `addVertex'| >prototype for `TCSGraph TCSGraph::addVertex(int)' does not match any in class `TCSGraph'| >error: candidate is: void TCSGraph::addVertex(int)| >error: `TCSGraph TCSGraph::addVertex(int)' and `void TCSGraph::addVertex(int)' cannot be overloaded
sum1needhelp
oh thx alot ^^it's work xD
sum1needhelp
oic, haha. thx agn =D
sum1needhelp
A: 

Have you taken a look at Boost Graph Library and boost::adjacency_list?

Potatoswatter