Reputation: 21
I have been working on this assignment for a while now and am quite stuck with inserting into my non-STL list. The code will compile successfully, but segfaults every time it goes to insert into my list. Below is some relevant code.
tripper.h:
class adjNode
{
public:
int vertex;
int weight;
adjNode(int v, int w) : vertex(v), weight(w) { }
adjNode() { }
};
tripper.cpp:
Tripper::Tripper(Road *roads, int numRoads, int size)
{
List <adjNode> adjList[numRoads];
for (int i=0; i<numRoads; i++) //Doesn't work with either line
{
adjList[roads[i].city1].push_back(adjNode(roads[i].city2, roads[i].distance));
//adjList[0].push_back(adjNode(2, 15)); //Really it's nothing but 3 integers involved
}
for (int i=0; i<9; i++)
{
for (List<adjNode>::iterator itr = adjList[i].begin(); itr != adjList[i].end(); itr++)
{
cout << "There is an edge going from " << i << " to " << (*itr).vertex;
cout << " with a weight of " << (*itr).weight << endl;
}
}
} // Tripper()
list.h:
void push_back( const Object & x )
{
insert( end( ), x );
}
iterator insert( iterator itr, const Object & x )
{
Node *p = itr.current;
theSize++;
return iterator( p->prev = p->prev->next = new Node( x, p->prev, p ) );
}
Node
struct Node {
Object data;
Node *prev;
Node *next;
Node( const Object & d = Object( ), Node * p = NULL, Node * n = NULL )
: data( d ), prev( p ), next( n )
{
}
};
Upvotes: 2
Views: 384
Reputation: 7287
return iterator( p->prev = p->prev->next = new Node( x, p->prev, p ) );
This line will crash if p->prev is NULL.
Upvotes: 1
Reputation: 25690
Use pen and paper and draw arrows for your pointer ops.
Separate the ops on different lines to be able to express your intent and debug the code more easily.
Upvotes: 0