Implemented class list , problems have problems with the Insert method. This method also works as in the LIST library, i.e. I transmit a position to the function to insert and the value itself, while the list size does not increase, it simply replaces the value of the item in a given position. At the very beginning and in the end everything is correctly inserted, and with the rest of the problem.
void insert (const int index, const t & amp; value) {
Element & lt; T & GT; * NewElem = New Element & lt; T & GT; (Value);
int Curindex = 0;
Element & lt; T & GT; * CUR = _FRONT;
While (Cur! = NullPTR)
{
if (index == 0)
{
// If index = 0 is entered, I change the values using the designer
// First Element
_Front = New Element & lt; T & GT; (value, _front- & gt; getNext (), _ Front- & gt; getprev ());
}
if (index == _SIZE-1)
{
// If index = Size is entered (the size of my list), with
// Designer I change the values of the last element
_back = new element & lt; t & gt; (value, _back- & gt; getNext (), _back- & gt; getprev ());
}
if (index & lt; 0)
{
Return;
}
if (Curindex == index-1)
{
// setNext () - the method that indicates the next element
// SETZKUM () - The method that indicates the previous element
NEWELEM- & GT; SETNEXT (CUR- & GT; getNext ());
NEWELEM- & GT; setPrev (CUR- & GT; GetPrev ());
CUR- & GT; SETNEXT (NEWELEM);
}
Curindex ++;
CUR = CUR- & GT; getNext ();
}
}
How do this method more correctly implement?
Answer 1, Authority 100%
You have a strange insert. It turns out: here in the first line:
element & lt; t & gt; * newelem = new element & lt; t & gt; (value);
You have created a new item, and then:
if (index == 0)
{
// If index = 0 is entered, I change the values using the designer
// First Element
_Front = New Element & lt; T & GT; (value, _front- & gt; getNext (), _ Front- & gt; getprev ());
}
still stands out. In this case, without deleting the memory under _Front
. That is, you lose the memory twice. The same after the line if (index == _Size-1)
You can approximately this:
void insert (const int index, const t & amp; value) {
Element & lt; t & gt; * current = _front;
for (int i = 0; i & lt; = index; ++ i)
Current = Current- & gt; getNext ();
CURRENT- & GT; SETVALUE (VALUE);
}
Add the setValue
method to the Element
class and you do not need to allocate dynamic memory again. This is a schematic example without taking into account that the user can pass an invalid index.