graph using adjacency list

 DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

# Thread: graph using adjacency list

1. Registered User
Join Date
Apr 2010
Posts
1

## create graph

#include<iostream>

using namespace std;

class Graph{
public:
void addVertex(int vertex);
void display();
TCSGraph(){

head = NULL;
}
~Graph(){}

private:
struct ListNode
{
string name;
struct ListNode *next;
};

ListNode *head;
};

void Graph::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;
newNode->next = NULL;

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

nodePtr->next = newNode;

}
}
}

void Graph::display(){
ListNode *nodePtr;
nodePtr = head;

while(nodePtr){
cout << nodePtr->name<< endl;
nodePtr = nodePtr->next;
}
}

void displayMenu(){
cout << endl << endl;
cout << " 1. Add a vertice" << endl;
cout << " 2. Displaying a graph by printing out the adjacency lists" << endl;
cout << " 0. Quit" << endl;
cout << endl;
cout << "Please enter your option: ";
}

int main(){

int choice;
int vertex;
bool done = false;

do{
displayMenu();
cin >> choice;
TCSGraph g;

if(choice==1){
cout << " how many vertex u wan to add" << endl;
cin >> vertex;
g.addVertex(vertex);
}
else if (choice==2){
g.display();
}
}while(!done);

return 0;
}
Last edited by ITNoob; 04-22-2010 at 04:12 AM.

2. Registered User
Join Date
Apr 2010
Posts
5
Hello,
your problem is that every pass of the loop, you create and destroy the TCSGraph object. Therefore it is always empty when you try to display it.
You have to put the declaration of the variable before the loop.

Second, you don't dealocate the dynamically created Nodes when TCSGraph is destroyed, which results in memory leaks.

And last but not least, if this is the verbatim source, learn to indent the code properly. It helps with reading and orientation immensely.

3. Senior Member
Join Date
Dec 2003
Posts
3,366
Originally Posted by MirekCerny
Hello,
your problem is that every pass of the loop, you create and destroy the TCSGraph object. Therefore it is always empty when you try to display it.
You have to put the declaration of the variable before the loop.

Second, you don't dealocate the dynamically created Nodes when TCSGraph is destroyed, which results in memory leaks.

And last but not least, if this is the verbatim source, learn to indent the code properly. It helps with reading and orientation immensely.
The web site destroys indention unless you use [CODE and [/CODE tags.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise
 Questions? Contact us. C++ Web Development Wireless Latest Tips Open Source