I am trying to create a graph from a 2d matrix of booleans. When the index [i][j] == 1, I need to create a link or edge from node[i] to node[j]. I am doing some thing wrong. I have created a class file with a struct node and some basic operations. I have realized a pointer of the struct in not the correct way to go about this. A node may have more than one edge to other nodes, and one pointer is not going to link them. Please help a struggling programming student. My code and output is listed below.
//LinkNode.h
#ifndef LINKNODE_H
#define LINKNODE_H
#include <string>
#include <iostream>
using namespace std;
class LinkNode
{
private:
typedef struct Node
{
string msg;
int data;
Node * next_node;
} * nodePtr;
nodePtr root;
nodePtr newNode;
nodePtr head;
nodePtr tempPtr;
public:
LinkNode();
void addNode(int addData);
void printList();
};
#endif
//LinkNode.cpp
#include "LinkNode.h"
#include <iostream>
#include <cstdlib>
using namespace std;
LinkNode::LinkNode()
{
head = tempPtr = root = NULL;
//next_node = NULL;
}
void LinkNode::addNode(int addData)
{
if(root == NULL)
{
root = new Node;
root->next_node = NULL;
root->data = addData;
}
else
{
tempPtr = root; // temp variable ptr
while(tempPtr->next_node != NULL) //find the last node
tempPtr = tempPtr->next_node; //in the linked list
newNode = new Node();
newNode->data = addData;
newNode->next_node = NULL;
tempPtr->next_node = newNode;
}
}
void LinkNode::printList()
{
tempPtr = root;
while(tempPtr != NULL)
{
cout << tempPtr->data << endl;
tempPtr = tempPtr->next_node;
}
}
//main.cpp
/*////////////////////////////////////////////////////////////////////
// //
// (N0) 0-------------------0\ (N1) //
// | / | \ //
// | / | \ //
// | / | \ //
// | / | \ //
// | / | 0 (N2) //
// | / | / //
// | / | / //
// | / | / //
// | / | / //
// (N4) 0-------------------0/ (N3) //
// //
// N = Nodes //
// The adjacency matrix for the graph is listed below. //
*/////////////////////////////////////////////////////////////////////
#include <iostream>
#include <array>
#include <string>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <exception>
#include "Stack.h"
#include "LinkNode.h"
using namespace std;
const int adjmatrix[5][5] = {
{0,1,0,0,1},
{1,0,1,1,1},
{0,1,0,1,0},
{0,1,1,0,1},
{1,1,0,1,0},
};
// create nodes
LinkNode Graph;
for(int i=0; i<5; i++)
for(int j=0; j<5; j++)
{
if(adjmatrix[i][j] == 1)
{
Graph.addNode(i);
Graph.printList();
}
}
cout << endl << endl << endl;
system("pause");
return 0;
}
// output
0
0
0
0
0
1
0
0
1
1
0
0
1
1
1
0
0
1
1
1
1
0
0
1
1
1
1
2
0
0
1
1
1
1
2
2
0
0
1
1
1
1
2
2
3
0
0
1
1
1
1
2
2
3
3
0
0
1
1
1
1
2
2
3
3
3
0
0
1
1
1
1
2
2
3
3
3
4
0
0
1
1
1
1
2
2
3
3
3
4
4
0
0
1
1
1
1
2
2
3
3
3
4
4
4