NOTE: THIS IS FOR HOMEWORK SO PLEASE DO NOT INCLUDE BLOCKS OF CODE IN YOUR ANSWERS
I have an assignment that requires us to implement a doubly linked list class. For some reason they defined the node struct as follows:
struct node {
node *next;
node *prev;
T *o;
};
It seems to me that it would be a lot easier to write the class if the struct member 'data' were not a pointer. Needless to say I can't change it so I'm going to have to just work around it. I tried implementing the method that adds an element to the beginning of the list as follows:
template <typename T>
void Dlist<T>::insertFront(T *o) {
node *np = new node;
T val = *o;
np->o = &val;
np->prev = NULL;
np->next = first;
if (!isEmpty()) {
first->prev = np;
} else {
last = np;
}
first = np;
}
While using ddd to debug I realized that everything works fine the first time you insert a number but the second time around everything gets screwed up since as soon as you set 'val' to the new element it "overwrites" the first one since the memory address of val was used. I tried doing other things like instead of just having the 'val' variable doing the following:
T *valp = new T;
T val;
valp = &val;
val = *o;
np->o = valp
This didn't seem to work either. I think this is because it's pretty much just a more complicated form of what I did above just with an additional memory leak :)
Any ideas/pointers in the right direction would be great.