#pragma once
#define V_TPLS template<class T>\
void MyList<T>::
template<class T>
class MyList
{
T data;
MyList* next, *back;
public:
MyList()
{
next = this;
back = this;
data = 0;
}
//在链表后插入数据
void push_back(T data);
//在链表前插入数据
void push_front(T data);//前继
//清空整个链表
void _clear()
{
while (this->next!=this)
{
MyList *temp = this->next;
this->next = this->next->next;
delete temp;
}
}
void put()
{
MyList *p = this->next;
while (p!=this)
{
cout << p->data << ends;
p = p->next;
}
}
~MyList()
{ _clear(); }
};
//在链表后插入数据
V_TPLS push_back(T data)
{
MyList *temp = new MyList;
temp->data = data;
static MyList*p_n = this;
temp->next = p_n->next;
temp->back = p_n;
p_n->next = temp;
p_n = p_n->next;
this->back = temp;
}
//在链表前插入数据
V_TPLS push_front(T data)
{
MyList *temp = new MyList;
temp->data = data;
temp->next = this->next;
temp->back = this;
this->next->back = temp;
this->next = temp;
}
为什么我的_clear()运行的时候this指针的地址为什么会改变呢?
每次运行到_clear()函数时就会报错
_clear() push_back() push_front()函数都有问题,改了三个函数的代码,你参照看下。
void _clear()
{
while (this->next != this)
{
MyList *temp = this->next;
this->next = temp->next;
temp->next->back = temp->back;
temp->next = temp;
temp->back = temp;
delete temp;
}
}
//在链表后插入数据
V_TPLS push_back(T data)
{
MyList* newList = new MyList;
newList->data = data;
MyList* temp = this->next;
this->next = newList;
newList->next = temp;
newList->back = this;
temp->back = newList;
}
//在链表前插入数据
V_TPLS push_front(T data)
{
MyList* newList = new MyList;
newList->data = data;
MyList* temp = this->back;
this->back = newList;
newList->back = temp;
newList->next = this;
temp->next = newList;
}
_clear() push_back() push_front()函数都有问题
你的程序我试了试,还是不行,无法析构.但是我找到原因了,并不是我的函数体结构写的有问题,
此问题程序的关键是不能使用delete重载的运算符,而要使用free,这样就一点问题也没有了
不知道为什么delete总是会改变我的this指针,导致无法析构
//清空整个链表
V_TPLS _clear()
{
while (this->next != this)
{
MyList *temp = this->next;
this->next = this->next->next;
free(temp);
}
size = 0;
}
我还真不太了解delete与free的区别,但是这点区别就是我程序的bug所在之处