c++ - Creating a new instance of a class for a doubly linked list -
c++ - Creating a new instance of a class for a doubly linked list -
i have been provided starter code creating doubly linked list. problem i'm having implementing function inserts newly created node @ 'head'.
a node in linked list next struct:
template <class t> struct listitem { t value; listitem<t> *next; listitem<t> *prev; listitem(t theval) { this->value = theval; this->next = null; this->prev = null; } };
the code insertion @ head under:
void list<t>::insertathead(t item) { listitem<int> a(item); //create node specified value if(head==null) { head=&a; //when list empty, set head //to address of node } else { //when list not empty, following. head->prev=&a; a.next=head; head=&a; } }
now problem is, when i'm supposed create new class object different memory address whenever insert item. i'm doing above updates same memory location. need know how create new class object.
what doing wrong, , potentially unsafe (using pointers local variables). need allocate new node new
expression:
listitem<int>* = new listitem<int>(item);
of course, when done list, have remember free memory delete
.
c++ class linked-list
Comments
Post a Comment