I am fairly new to C++ so if this is a silly question I apologize.
I am trying to create a graph algorithm and I have been stuck on a problem for quite sometime.
I am trying to set my head pointer (adjacent) to a new dynamically node (of type ListNode).
I am confused because when dynamically allocating memory for each vertex I dont have a problem. But when trying to access them individually through a subscript I am receiving errors.
Please see my code and errors below:
#include "stdafx.h"
#include <iostream>
//node for the linked list
struct ListNode
{
int vertexNumber;
ListNode *next;
};
struct Graph
{
int vertex;
int edge;
ListNode *adjacent; //array of head pointers to linked list
};
Graph *adjListOfGraph();
int main()
{
return 0;
}
Graph *adjListOfGraph()
{
int i, x, y;
ListNode *temp;
//graph created
Graph *g = new Graph;
if (!g)
{
std::cout << "Memory Error" << std::endl;
return 0;
}
std::cout << "Enter number of vertices: " << std::endl;
std::cin >> g->vertex;
std::cout << "Enter number of edges: " << std::endl;
std::cin >> g->edge;
//dynamically allocate memory for each vertex
g->adjacent = new ListNode[g->vertex];
for (int i = 0; i < g->vertex; i++)
{
g->adjacent[i] = new ListNode; //error; no operator "=" matches these operands
g->adjacent[i].vertexNumber = i;
g->adjacent[i].next = g->adjacent[i]; //error; no suitable conversation
}
I know there are better ways to great a graph algorithm and I plan to create one through smart pointers and vectors after. But I am trying to follow a book (which is written in C) and I am having trouble duplicating the code.
Any help or advice would be much appreciated.